同时输出到控制台和文件

问题描述 投票:0回答:1

但是:

  1. 没有外部 shell 命令,例如
    | tee
  2. 没有新函数和语法更改,例如,继续按原样使用
    print()
python
1个回答
0
投票

您可以创建一个派生自

io.TextIOBase
的自定义类,并且可以作为
file=
参数传递给
print
,并通过将相同内容写入多个其他文件对象来在内部处理对
.write()
的调用.

实现示例:

import io
import sys
from typing import TextIO

class MultiTextIO(io.TextIOBase):
    def __init__(self, *fds: TextIO):
        self.fds = fds

    def read(self, n=-1, /):
        raise NotImplementedError("read not implemented, where would I read from?")

    def write(self, b, /):
        for fd in self.fds:
            fd.write(b)

fp = open(sys.argv[1] if 1 < len(sys.argv) else "output.txt", "w")
multi_output_io = MultiTextIO(sys.stdout, fp)

print("Hello, World!", file=multi_output_io)

使用示例:

$ python output2.py
Hello, World!
$ cat output.txt
Hello, World!
© www.soinside.com 2019 - 2024. All rights reserved.