【发布时间】:2011-08-10 21:03:30
【问题描述】:
我认为print 语句只是在sys.stdout(默认情况下)对象上调用了 .write() 方法。
但是写了一个这样的子类:
import time
class logfile(file):
def __init__(self, *args, **kwargs):
file.__init__(self, *args, **kwargs)
def write(self, logstr):
if logstr[-1] != '\n': logstr += '\n'
super(logfile, self).write(time.strftime('%D-%T ') + str(logstr))
如果我创建一个logfile 对象并调用write 方法似乎可以工作,但是当尝试将sys.stdout 对象更改为logfile 的一个实例时,它看起来好像print 不是' t 打电话给write。也许writelines?
使用这个:
#!/usr/bin/python
from myfile import logfile
import sys
sys.stdout = logfile('somefile', 'w')
print 'this is a test'
sys.stdout.write('this is another test')
我的输出文件“somefile”包含:
this is a test
08/10/11-16:59:47 this is another test
你可以看到输出文件的第一行是我尝试print的内容,第二行是sys.stdout.write中使用的内容
我以为 print 只是调用了 write 方法——显然我缺少一些基本的东西。
【问题讨论】:
-
print有自己对stdout的引用。 -
@Evpok 我认为如果他尝试重定向打印而不是使用普通日志记录,他可能不想修改预先存在的
print语句。 -
您应该使用日志记录模块来记录文件。更可配置。
-
您是故意避免使用 Python 的日志记录模块,还是这只是替代实现中的练习?
标签: python oop file inheritance printing