我正在使用名为 dis
的 python 模块来分析字节码。默认情况下,dis
会将输出发送到屏幕。我想在不修改 dis
模块的情况下将 dis
的输出重定向到一个文件。问题是,在某些条件为真后,我从一个长程序中调用 dis
。我举个例子!
class foo(object):
def method1():
print 'something'
name = 6
print name
class boo(object):
def method1():
print 'nothing'
name = 10
print name
import dis
# other statements
if foo.method1.im_func.func_code.co_code != boo.method1.im_func.func_code.co_code:
dis.dis(method1) # would like to redirect output to a file
dis.dis(method2) # would like to redirect output to a file
# other statements
使用 sys.stdout = open('file', 'w')
将所有内容发送到文件。然而,有一些声明是主程序的一部分,我希望在程序运行时在屏幕上看到这些声明。
最佳答案
您可以在调用 dis
例程之前和之后设置和重置 sys.stdout
:
sys.stdout = dis_output_file
dis.dis(method1)
dis.dis(method2)
sys.stdout = sys.__stdout__
sys.__stdout__
始终指代应用程序的实际标准输出。
当然,如果您使用多线程,这种方法就会失败。
关于python:将标准输出选择性重定向到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6135617/