我认为 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
没有调用 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
您可以看到输出文件中的第一行是我尝试打印
的内容,第二行是sys.stdout.write
中使用的内容
我认为 print
只是调用了 write
方法 - 显然我遗漏了一些基本的东西。
最佳答案
显然,这是 Python 2 实现的一个限制,其中 print 是一个语句而不是具有副作用的表达式(就像在 Python 3 中一样)。
我将代码重写为适用于 Python 3 的代码:
from io import FileIO
import time
class logfile(FileIO):
def __init__(self, *args, **kwargs):
FileIO.__init__(self, *args, **kwargs)
def write(self, logstr):
if logstr[-1] == '\n': logstr = logstr[:-1]
super(logfile, self).write(bytes(time.strftime('%D-%T ') + str(logstr), 'UTF-8'))
import sys
sys.stdout = logfile('somefile', 'w')
print("This is a test")
sys.stdout.write('this is another test')
据我所知,无法在 Python 2 中创建相同的行为。
我也尝试过使用 from __future__ import print_function
但这没有任何区别。
关于pythons 'print' 语句不调用 .write() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7017778/