包装器写入多个流

时间:2012-02-03 15:04:40

标签: python file-io

在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。我知道写自己的很容易,但如果有现有的,我宁愿使用它而不必担心找到并覆盖边缘情况。

3 个答案:

答案 0 :(得分:3)

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()

答案 1 :(得分:2)

包装所有公共file函数的方法:

import sys

def _call_for_all_streams(func_name):
    def wrapper(self, *args, **kwargs):
        result = []
        for stream in self._streams:
            func = getattr(stream, func_name)
            result.append(func(*args, **kwargs))
        return result
    return wrapper

class OStreamWrapper(object):
    def __init__(self, *streams):
        self._streams = streams

for method in filter(lambda x: not x.startswith('_'), dir(file)):
    setattr(OStreamWrapper, method, _call_for_all_streams(method))

if __name__ == '__main__':
    file1 = open("file1.txt", "w")
    file2 = open("file2.txt", "w")
    ostream = OStreamWrapper(file1, file2, sys.stdout)
    ostream.write("ECHO!")
    ostream.close()

但它有点脏。

答案 2 :(得分:0)

Logbook是另一种选择,尽管它不止于此。它的处理程序更强大,你可以随意组合。