如何捕获另一个模块的打印输出? [英] How to capture print output of another module?

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

问题描述

我想知道这在 python 中是否可行:

I was wondering if this is possible in python:

# module1
def test():
    print('hey')

# module2
import module1

module1.test() # prints to stdout

在不修改 module1 的情况下,有什么方法可以将其包装在 module2 中,以便我可以捕获print('hey') 在变量中?除了将 module1 作为脚本运行?

Without modifying module1 is there any way to wrap this in module2 so that I can capture the print('hey') inside a variable? Apart from running module1 as a script?

推荐答案

是的,你可以.您需要控制 sys.stdout.像这样:

Yes, you can. You need to take control of sys.stdout. Something like this:

import sys

stdout_ = sys.stdout #Keep track of the previous value.
sys.stdout = open('myoutputfile.txt', 'w') # Something here that provides a write method.
# calls to print, ie import module1
sys.stdout = stdout_ # restore the previous stdout.

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

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