问题
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