gpt4 book ai didi

python - 写入多个流的包装器

转载 作者:太空宇宙 更新时间:2023-11-03 14:32:00 24 4
gpt4 key购买 nike

在 python 中,是否有一种简单的方法来设置一个类似文件的对象来写入,该对象实际上由多个输出流支持?例如,我想要这样的东西:

file1 = open("file1.txt", "w")
file2 = open("file2.txt", "w")
ostream = OStreamWrapper(file1, file2, sys.stdout)

#Write to both files and stdout at once:
ostream.write("ECHO!")

所以我正在寻找的是OStreamWrapper。我知道自己编写会很容易,但如果有现成的,我宁愿使用它,而不必担心查找和覆盖边缘情况。

最佳答案

class OStreamWrapper(object):

def __init__(self, *streams):
self.streams = list(streams)

def write(self, string):
for stream in self.streams:
stream.write(string)

def writelines(self, lines):
# If you want to use stream.writelines(), you have
# to convert lines into a list/tuple as it could be
# a generator.
for line in lines:
for stream in self.streams:
stream.write(line)

def flush(self):
for stream in self.streams:
stream.flush()

关于python - 写入多个流的包装器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9130755/

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