python:选择性地将标准输出重定向到文件
我正在使用名为 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') 将所有内容发送到文件。然而,有一些语句是主程序的一部分,我希望在程序运行时看到打印在屏幕上。
I am using python's module called dis
for analysis of bytecode. By default dis
will send the output to the screen. I would like to re-direct the output of dis
to a file without modifying dis
module. The problem is, i call dis
from within a long program after some condition is true. I will give an example!
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
using sys.stdout = open('file', 'w')
sends everything to a file. However there are some statments which are part of the main program i would like to see printed on the screen as the program is running.
您可以在调用
dis
例程之前和之后设置和重置sys.stdout
:sys.__stdout__
始终引用应用程序的实际标准输出。当然,如果使用多线程,这种方法就会失败。
You can set and reset
sys.stdout
before and after callingdis
routines:sys.__stdout__
always refers to the actual standard output of your application.Of course, if you are using multiple threads, this approach would fail.