你如何在Python中子类化文件类型?

Ada*_*eld 13 python file subclass

我正在尝试使用filePython 子类化内置类来为stdin和添加一些额外的功能stdout.这是我到目前为止的代码:

class TeeWithTimestamp(file):
    """
    Class used to tee the output of a stream (such as stdout or stderr) into
    another stream, and to add a timestamp to each message printed.
    """

    def __init__(self, file1, file2):
        """Initializes the TeeWithTimestamp"""
        self.file1 = file1
        self.file2 = file2
        self.at_start_of_line = True

    def write(self, text):
        """Writes text to both files, prefixed with a timestamp"""

        if len(text):
            # Add timestamp if at the start of a line; also add [STDERR]
            # for stderr
            if self.at_start_of_line:
                now = datetime.datetime.now()
                prefix = now.strftime('[%H:%M:%S] ')
                if self.file1 == sys.__stderr__:
                    prefix += '[STDERR] '
                text = prefix + text

            self.file1.write(text)
            self.file2.write(text)

            self.at_start_of_line = (text[-1] == '\n')
Run Code Online (Sandbox Code Playgroud)

目的是在每条消息的开头添加一个时间戳,并将所有内容记录到日志文件中.但是,我遇到的问题是,如果我这样做:

# log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
Run Code Online (Sandbox Code Playgroud)

然后,当我尝试做的时候print 'foo',我得到一个ValueError: I/O operation on closed file.我不能有意义地打电话给file.__init__()__init__(),因为我不想打开一个新文件,我也不能分配self.closed = False,因为它是一个只读属性.

我如何修改它以便我可以这样做print 'foo',以便它支持所有标准file属性和方法?

Ale*_*lli 12

调用file.__init__是非常可行的(例如,在'/ dev/null'上),但是没有实际用途,因为你试图覆盖writeprint语句没有"接受" 语句 - 后者file.write在看到它sys.stdout是实际时内部调用真实的file(通过继承你已经成功了)的实例.

print实际上并不需要任何其他方法write,所以让你的类继承object而不是file工作.

如果你需要其他文件方法(也就是说,print你不是在做什么),你最好自己实现它们.