Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Python中对文件类型进行子类化?_Python_File_Subclass - Fatal编程技术网

如何在Python中对文件类型进行子类化?

如何在Python中对文件类型进行子类化?,python,file,subclass,Python,File,Subclass,我试图在Python中对内置的文件类进行子类化,以向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. ""

我试图在Python中对内置的
文件
类进行子类化,以向
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')
其目的是在每条消息的开头添加时间戳,并将所有内容记录到日志文件中。但是,我遇到的问题是,如果我这样做:

# log_file has already been opened
sys.stdout = TeeWithTimestamp(sys.stdout, log_file)
然后,当我尝试执行
打印'foo'
时,我得到了一个
ValueError:I/O操作,操作对象是关闭的文件
。我不能有意义地调用
文件。
中的
\uu init\uu()
,因为我不想打开新文件,也不能分配
self.closed=False
,因为它是只读属性


我如何修改它,以便我可以打印'foo',并使它支持所有标准的
文件
属性和方法?

调用
文件。uuuu init_uuu
是非常可行的(例如,在'/dev/null'),但没有实际的用途,因为您尝试的
重写不会“占用”对于
print
语句,后者在看到
sys.stdout
文件
的实际实例时(通过继承,您已经这样做了),会在内部调用real
file.write

print
实际上不需要除
write
之外的任何其他方法,因此使类从
对象继承而不是从
文件继承将起作用


如果您需要其他文件方法(即,
print
并不是您所要做的全部),建议您自己实现它们。

您也可以避免使用
super

class SuperFile(file):

    def __init__(self, *args, **kwargs):
        file.__init__(self, *args, **kwargs)

你可以用它来写。

我不确定我需要什么样的函数,但我当然希望实现一些更常用的函数。我想我会咬紧牙关,实现我所需要的,并从对象而不是文件派生。除了write,sys.stdout上通常使用哪些方法?也许writelines,close,flush--所有这些都非常简单(而且你必须自己实现它们--文件类型怎么知道关闭或刷新两个文件呢?-)是的,你是对的,在查看文件接口时,我真正需要的是write,writelines,close,flush。任何其他内容都不应该在sys.stdout或sys.stderr上调用。