Assign a function output prints to a variable in python

╄→гoц情女王★ 提交于 2019-12-25 08:12:46

问题


I have a function (in some project) that it prints the result.when I call it from the command line or in another python project, it prints the output on the terminal. But I want to store all the print result in a variable, something like this:

output = function_name(function_args)

and instead of printing the results on the terminal I want to store them in the output variable. also, the main function returns something(just a number as the status) as the result which i do not want that number.


回答1:


You can do this by rebinding sys.stdout:

>>> def foo():
...     print('potato')
... 
>>> import sys, io
>>> sys.stdout = io.StringIO()
>>> foo()
>>> val = sys.stdout.getvalue()
>>> sys.stdout = sys.__stdout__  # restores original stdout
>>> print(val)
potato

For a nicer way to do it, consider writing a context manager. If you're on Python 3.4+, it's already been written for you.

>>> from contextlib import redirect_stdout
>>> f = io.StringIO()
>>> with redirect_stdout(f):
...     foo()
... 
>>> print(f.getvalue())
potato



回答2:


The sensible solution is simple and obvious: fix the function so that it returns the correct data instead of printing it. Else you can use the hack posted by wim but assuming you have the hand on the faulty function resorting to such a convoluted solution falls into the "WTF" category.

NB of course if you don't have the hand on the function's code or it's just for a 5 minutes one-shot script, capturing sys.stdout is a handy fallback.



来源:https://stackoverflow.com/questions/41493230/assign-a-function-output-prints-to-a-variable-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!