gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 03:25:39 25 4
gpt4 key购买 nike

我有一些函数 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com