Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
614 views
in Technique[技术] by (71.8m points)

terminal - Assign a function output prints to a variable in python

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

In the case that you are able to modify the function itself, it may be cleaner to allow a dependency injection of the output stream (this is just a fancy way of saying "passing arguments"):

def foo(file=sys.stdout):
    print('potato', file=file)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...