python:stdout选择性重定向到文件

问题描述

|| 我正在使用名为
dis
的python模块来分析字节码。默认情况下,“ 0”会将输出发送到屏幕。我想将“ 0”的输出重定向到一个文件,而无需修改“ 0”模块。问题是,在满足某些条件后,我从一个长程序中调用了“ 0”。我举一个例子!
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__
始终是指应用程序的实际标准输出。 当然,如果您使用多个线程,则此方法将失败。     

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...