Skip to main content
 首页 » 编程设计

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

2025年05月04日16yyy_WW

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

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