python - 忽略基于子字符串的某些打印语句

标签 python python-3.x printing

我有一些函数 f 调用了一些生成相当多不必要的打印语句的库。我不能简单地删除所有打印的值,因为这会使调试变得不可能。然而,有些事情总是打印出来,我确实想忽略。假设我想忽略(不显示)任何包含子字符串“substring”的打印行。有没有办法做一些事情:

def g():
    print('why is this substring being printed')
    return 1
def f():
    print('this should be printed')
    return g()
# now run with magic function
with IgnorePrints(substring='substring'):
    result = f()

如果此代码与 IgnorePrints 一起运行,它只会导致:

this should be printed

最佳答案

使用 contextlib.redirect_stdout :

import sys
from contextlib import redirect_stdout

class PrintFilter:
    def __init__(self, stream, substring):
        self.stream = stream
        self.substring = substring

    def write(self, txt):
        if self.substring not in txt:
            self.stream.write(txt)


my_filter = PrintFilter(stream=sys.stdout, substring="substring")

with redirect_stdout(my_filter):
    result = f()

关于python - 忽略基于子字符串的某些打印语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67655005/

相关文章:

python - Tkinter:调度通过按钮单击执行的顺序线程

python - 如何替换Python字典中的二维列表值?

java - PDFBox: 打印后立即显示 "you did not close a PDFDocument"

python - Django 中 MySQL 配置不正确

Python 按给定顺序将多个文件 append 到一个大文件

python - Pandas `drop_duplicates` 不保留第一行

python-3.x - 使用ffmpeg从MP4文件中仅提取Y(YUV420p)帧?

java - 如何调用JFreeChart的打印选项

printing - ARM 汇编以十进制形式打印寄存器值

python - 如何从图像中去除颜色