如何从函数中实时捕获打印内容?

2024-03-23

我想捕捉所有prints 并执行诸如返回它们之类的操作,但继续运行该函数。 我找到了这个方法,但它只返回print代码完成后。

f = io.StringIO()
with redirect_stdout(f):
    # my code

return f.getvalue()

有没有什么方法可以捕捉到每一个print实时?


您可以编写自己的类似文件的对象,在看到文本行时对其进行处理。在最简单的情况下,您只需要提供一个write方法如下图。棘手的部分是知道“打印”调用何时完成。print可能会打电话stdout.write多次执行单个打印操作。在此示例中,每当看到换行符时我都会进行处理。此代码不返回临时打印,但允许您拦截对 stdout 的写入并在返回调用 print 的函数之前对其进行处理。

from contextlib import redirect_stdout
import sys

real_stdout_for_test = sys.stdout

class WriteProcessor:

    def __init__(self):
        self.buf = ""

    def write(self, buf):
        # emit on each newline
        while buf:
            try:
                newline_index = buf.index("\n")
            except ValueError:
                # no newline, buffer for next call
                self.buf += buf
                break
            # get data to next newline and combine with any buffered data
            data = self.buf + buf[:newline_index + 1]
            self.buf = ""
            buf = buf[newline_index + 1:]
            # perform complex calculations... or just print with a note.
            real_stdout_for_test.write("fiddled with " + data)
            
with redirect_stdout(WriteProcessor()):
    print("hello there")
    print("a\nprint\nof\nmany\nlines")
    print("goodbye ", end="")
    print("for now")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从函数中实时捕获打印内容? 的相关文章

随机推荐