我認爲print
聲明只是在sys.stdout
(默認)對象上調用.write()方法。pythons'print'語句不調用.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
不叫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
方法,很明顯我很想念計算基本。
http://stefaanlippens.net/redirect_python_print是否有幫助? – Evpok
'print'有它自己對'stdout'的引用。 – agf
@Evpok我想如果他試圖重定向打印而不是使用正常的日誌記錄,他可能不想修改預先存在的'print'語句。 – agf