Python捕获所有打印输出 [英] Python capture all printed output

查看:676
本文介绍了Python捕获所有打印输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找用python编写基于控制台的程序,该程序可以执行功能以执行通用任务,相当通用.是否可以通过函数中的打印调用捕获所有写入控制台的内容,而无需返回字符串,类似于bash和Windows Shell允许将程序输出管道传输到文本文件的方式,即

I am looking to write console based programs in python that can execute functions to perform generic tasks, pretty generic. Is it possible to capture everything written to the console by print calls in a function without needing to return a string, similar to how bash and the windows shell allow piping the output of a program to a text file, ie

ipconfig> ipconfig.txt

ipconfig>ipconfig.txt

但是在python程序内部执行此操作,在该程序中调用函数,该函数内部打印到控制台的所有内容都作为字符串列表收集,然后可以保存到用户选择的txt文件中?

but doing this inside of a python program, where a function is called, everything that was printed to the console inside of that function is gathered as a list of strings, and then can be saved to a txt file of the users choice?

推荐答案

您可以通过将sys.stdout设置为您选择的文件来实现

You can do this by setting sys.stdout to be a file of your choice

import sys

sys.stdout = open('out.dat', 'w')
print "Hello"

sys.stdout.close()

将不显示任何输出,但将创建带有打印文本的名为out.dat的文件.

Will not display any output but will create a file called out.dat with the printed text.

请注意,这不必是实际文件,而可以是 StringIO 实例,您可以使用getvalue方法访问以前打印过的所有内容.

Note that this doesn't need to be an actual file but could be a StringIO instance, which you can just use the getvalue method of to access everything that has been printed previously.

这篇关于Python捕获所有打印输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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