将函数输出输出分配给python中的变量 [英] Assign a function output prints to a variable in python
问题描述
我有一个函数(在某些项目中),它会打印结果.当我从命令行或另一个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)
,而不是将结果打印在终端上,我想将它们存储在output
变量中.
同样,main函数返回一些结果(只是一个数字作为状态),结果我不想那个数字.
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.
推荐答案
您可以通过重新绑定sys.stdout
来做到这一点:
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
要获得更好的方法,请考虑编写上下文管理器.如果您使用的是Python 3.4+,则已经为您编写了.
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
这篇关于将函数输出输出分配给python中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!