【问题标题】:Specific print statement wrapper in python to ignore either out or error messagespython中的特定打印语句包装器忽略输出或错误消息
【发布时间】:2021-10-21 15:11:20
【问题描述】:

我希望创建一个 python 包装器来捕获和丢弃由我正在使用的库生成的特定文本,并且我无法以通常的方式摆脱它们,即

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 my_program.py 2>&1; } | grep -v "string-to-ignore"

但是这有点不太理想,因为它很难忽略多个字符串。有没有一种简单的方法可以将我的 main 函数以与上面介绍的包装函数类似的方式包装在 my_program.py 中?

【问题讨论】:

  • 抱歉没看懂,请问您的解决方案有什么问题?
  • 这个{ python my_program.py 2>&1; } | grep -v "string-to-ignore" 有效,但是我不想在每次运行访问它的函数时包装使用这个库的所有程序。相反,我希望能够在我的 python 脚本中添加一些可以自动执行此操作的内容。如果它有帮助的话,产生一堆语句的库是 pygame,它不使用打印,而是使用某种类型的日志记录。更重要的是,不是将消息定向到标准输出,而是将它们定向到标准错误。

标签: python filter printing stdout with-statement


【解决方案1】:

在实例化时只需更改您的PrintFilter 类以获取字符串列表而不是单个字符串。然后在决定是否应该省略消息时遍历该列表。

PS:我必须在您的问题中遗漏一个重要细节,因为解决方案似乎微不足道。也许您需要改写您的问题。

【讨论】:

    猜你喜欢
    • 2016-12-03
    • 2013-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-04
    • 2021-09-03
    • 2020-07-29
    • 2012-09-22
    相关资源
    最近更新 更多