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 statemen开发者_如何学运维ts
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.
You can set and reset sys.stdout
before and after calling dis
routines:
sys.stdout = dis_output_file
dis.dis(method1)
dis.dis(method2)
sys.stdout = sys.__stdout__
sys.__stdout__
always refers to the actual standard output of your application.
Of course, if you are using multiple threads, this approach would fail.
精彩评论