python:将标准输出选择性重定向到文件

标签 python stdout

我正在使用名为 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/

相关文章:

python - Discord-py Rewrite - Cog 中的基本 aiohttp 网络服务器

python - 在 Pandas 数据框列的子集上使用 Pipeline 中的 scikit StandardScaler

Java 读取进程输出,无缓冲/实时

python - 如何在 Python 3 中设置 sys.stdout 编码?

从 Perl 调用的 Perl 脚本似乎没有刷新标准输出

c++ - 从 native c++ dll 将 stdout 重定向到 Visual Studio 输出窗口

python - 我需要从 Xpath 获取图像 src

python - BIC 使用 scikit-learn 中的 GaussianMixture 过度拟合图像分割模型中的组件数量

python - 按实体值对 tkinter 列表框中的项目进行排序

java - 为什么我没有得到任何输出?并且有一个InputMismatchException