python - 如何从 Python 中的标准输出重定向转义

标签 python python-3.x contextmanager stringio

我想处理第三方脚本的实时输出,打印一些与模式匹配但跳过其他行的行:

def thirdparty_code():
    from random import choice
    stuff = ['keep: important stuff', 'ignore: boring stuff']
    while True:
        chosen_line = choice(stuff)
        print(chosen_line)

我使用 redirect_stdout(将行传递到我的虚拟 IO)和一个扩展的 StringIO(用作 IO 但也调用我的过滤函数)。但是,当我在我的处理函数中调用 print() 时,我得到了一个 RecursionError - 这并不意外:

from io import StringIO
from contextlib import redirect_stdout

class StringIOWithCallback(StringIO):

    def __init__(self, callback, **kwargs):
        super().__init__(**kwargs)
        self.callback = callback

    def write(self, s):
        super().write(s)
        self.callback(s)

def filter_boring_stuff_out(line):
    if line.startswith('ignore'):
        return
    print(line)

my_io = StringIOWithCallback(filter_boring_stuff_out)

with redirect_stdout(my_io):
    thirdparty_code()

我想知道是否有可能从重定向中逃脱,例如在 print() 函数中指定 file 参数,以便它打印到实际的标准输出。我知道我可以轻松地使用标准错误流:

import sys
print(line, file=sys.stderr)

但我特别想使用标准输出。有没有一种很好的 pythonic 方式来做到这一点?

最佳答案

在重定向 stdout 之后,您可以轻松地重置它,这要归功于 __stdout__ 保存了原始值。

sys.stdout = redirected_stdout
...
...
sys.stdout = sys.__stdout__

如果你不断地发现自己切换这些输出流,你应该创建一个函数来输出到重定向的流:

def redirect(*args):
    print(*args, file=redirected_file)

redirect(...)  # redirect this output
print(...)  # use standard stream

关于python - 如何从 Python 中的标准输出重定向转义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260336/

相关文章:

python - Pandas - 如何创建从连续两行中的值派生的新列?

python - 使用Python的高多线程

python - 在多核上运行 Python

python - 从对象重建源

python - 如何打开一堆文件(使用上下文管理)而不嵌套一堆缩进

python - 如何将 sklearn MinMaxScaler() 的值转换回实际值?

python - 无法从 python 中的 random.shuffle 获得结果

python - 访问所有函数参数

python - 在 contextlib.contextmanager 中产生

python - 如何从with语句返回?