如何在Python中对文件类型进行子类化?
我试图在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. ""
文件
类进行子类化,以向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
是文件
的实际实例时(通过继承,您已经这样做了),会在内部调用realfile.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上调用。