将函数输出打印分配给python中的变量 [英] Assign a function output prints to a variable in python

查看:38
本文介绍了将函数输出打印分配给python中的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数(在某些项目中)可以打印结果.当我从命令行或另一个 python 项目调用它时,它会在终端上打印输出.但我想将所有打印结果存储在一个变量中,如下所示:

output = function_name(function_args)

而不是在终端上打印结果,我想将它们存储在 output 变量中.此外,主函数返回一些东西(只是一个数字作为状态)作为结果,我不想要那个数字.

解决方案

您可以通过重新绑定 sys.stdout 来实现:

<预><代码>>>>定义 foo():...打印('土豆')...>>>导入系统,io>>>sys.stdout = io.StringIO()>>>富()>>>val = sys.stdout.getvalue()>>>sys.stdout = sys.__stdout__ # 恢复原始标准输出>>>打印(val)土豆

要获得更好的方法,请考虑编写上下文管理器.如果您使用的是 Python 3.4+,则已经为您编写.

<预><代码>>>>从 contextlib 导入 redirect_stdout>>>f = io.StringIO()>>>使用 redirect_stdout(f):... foo()...>>>打印(f.getvalue())土豆

在您能够修改函数本身的情况下,允许输出流的依赖注入可能更清晰(这只是传递参数"的一种奇特方式):

def foo(file=sys.stdout):打印('土豆',文件=文件)

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.

解决方案

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)

这篇关于将函数输出打印分配给python中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆