python - 子函数的自定义打印函数 yield

标签 python python-3.x

我自定义了打印函数以打印到控制台,并将打印行发送到一个对象,这样我就可以使用 yield 函数将它们通过管道传输到 gui。这工作正常,直到我的函数调用一个子函数并且该子函数打印到控制台。如果我将我的自定义打印导入该子函数,它不起作用,因为该打印正在向子函数产生结果,而不是原始的外部函数。

有没有一种方法可以将自定义打印的结果直接返回到主函数并跳过这个开始式的噩梦?

from __future__ import print_function
import __builtin__

def print(*args, **kwargs):
    import builtins
    import io
    from contextlib import redirect_stdout
    builtins.print(*args, **kwargs)
    with io.StringIO() as buf, redirect_stdout(buf):
        builtins.print(*args, **kwargs)
        output = buf.getvalue()
    return output

最佳答案

不是覆盖 print,而是创建一个对象,当您写入时写入两个不同的文件。有点像

# I'm not sure if there are other methods you should override, but
# they would be similar.
class Delegator(io.TextIOBase):
    def __init__(self, fh1, fh2):
        self.fh1 = fh1
        self.fh2 = fh2

    def write(self, txt):
        self.fh1.write(txt)
        self.fh2.write(txt)

    def flush(self):
        self.fh1.flush()
        self.fh2.flush()

sys.stdout = Delegator(sys.stdout, my_other_file)

关于python - 子函数的自定义打印函数 yield ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49499282/

相关文章:

python - python处理500万个key-value数据,NoSql能解决吗?

python - 如何制作 5.1 和 7.1 环绕声文件

python - 如何在路径中发送带有两个参数的 DELETE 请求?

python - 打印以逗号分隔的项目列表,但在最后一项之前使用单词 "and"

python - wagtail AbstractImage、ParentalManyToManyField 和 ClusterableModel

python - 第 1 行的 SyntaxError : Non-UTF-8 code starting with '\x90' in file C:\Python36\python. exe,但未声明编码

python-3.x - 无法在 Google Colab 中将 Pytorch 模型保存到 Google Drive?

python - 使用matplotlib在单个pdf页面上保存多个图

python - 将 NumPy 对象与 "None"进行比较时出现 FutureWarning

来自多个文件的 Python txt 矩阵