一. 背景
在Python中,文件对象sys.stdin、sys.stdout和sys.stderr分别对应解释器的标准输入、标准输出和标准出错流。在程序启动时,这些对象的初值由sys.__stdin__、sys.__stdout__和sys.__stderr__保存,以便用于收尾(finalization)时恢复标准流对象。
Windows系统中IDLE(Python GUI)由pythonw.exe,该GUI没有控制台。因此,IDLE将标准输出句柄替换为特殊的PseudoOutputFile对象,以便脚本输出重定向到IDLE终端窗口(Shell)。这可能导致一些奇怪的问题,例如:
Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. >>> import sys >>> for fd in (sys.stdin, sys.stdout, sys.stderr): print fd <idlelib.PyShell.PseudoInputFile object at 0x0177C910> <idlelib.PyShell.PseudoOutputFile object at 0x0177C970> <idlelib.PyShell.PseudoOutputFile object at 0x017852B0> >>> for fd in (sys.__stdin__, sys.__stdout__, sys.__stderr__): print fd <open file '<stdin>', mode 'r' at 0x00FED020> <open file '<stdout>', mode 'w' at 0x00FED078> <open file '<stderr>', mode 'w' at 0x00FED0D0> >>></div>
可以发现,sys.__stdout__与sys.stdout取值并不相同。而在普通的Python解释器下(如通过Windows控制台)运行上述代码时,两者取值相同。
print语句(statement)不以逗号结尾时,会在输出字符串尾部自动附加一个换行符(linefeed);否则将一个空格代替附加的换行符。print语句默认写入标准输出流,也可重定向至文件或其他可写对象(所有提供write方法的对象)。这样,就可以使用简洁的print语句代替笨拙的object.write('hello'+'\n')写法。
由上可知,在Python中调用print obj打印对象时,缺省情况下等效于调用sys.stdout.write(obj+'\n')
示例如下:
>>> import sys
>>> print 'Hello World'
Hello World
>>> sys.stdout.write('Hello World')
Hello World
</div>
二. 重定向方式
本节介绍常用的Python标准输出重定向方式。这些方法各有优劣之处,适用于不同的场景。
2.1 控制台重定向
最简单常用的输出重定向方式是利用控制台命令。这种重定向由控制台完成,而与Python本身无关。
Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通过">"或">>"将输出重定向。其中,">"表示覆盖内容,">>"表示追加内容。类似地,"2>"可重定向标准错误。重定向到"nul"(Windows)或"/dev/null"(Linux)会抑制输出,既不屏显也不存盘。
以Windows命令提示符为例,将Python脚本输出重定向到文件(为缩短篇幅已删除命令间空行):
E:\>echo print 'hello' > test.py E:\>test.py > out.txt E:\>type out.txt hello E:\>test.py >> out.txt E:\>type out.txt hello hello E:\>test.py > nul</div>
注意,在Windows命令提示符中执行Python脚本时,命令行无需以"python"开头,系统会根据脚本后缀自动调用Python解释器。此外,type命令可直接显示文本文件的内容,类似Linux系统的cat命令。
Linux Shell中执行Python脚本时,命令行应以"python"开头。除">"或">>"重定向外,还可使用tee命令。该命令可将内容同时输出到终端屏幕和(多个)文件中,"-a"选项表示追加写入,否则覆盖写入。示例如下(echo $SHELL或echo $0显示当前所使用的Shell):
[wangxiaoyuan_@localhost ~]$ echo $SHELL /bin/bash [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" hello [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > out.txt [wangxiaoyuan_@localhost ~]$ cat out.txt hello [wangxiaoyuan_@localhost ~]$ python -c "print 'world'" >> out.txt [wangxiaoyuan_@localhost ~]$ cat out.txt hello world [wangxiaoyuan_@localhost ~]$ python -c "print 'I am'" | tee out.txt I am [wangxiaoyuan_@localhost ~]$ python -c "print 'xywang'" | tee -a out.txt xywang [wangxiaoyuan_@localhost ~]$ cat out.txt I am xywang [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > /dev/null [wangxiaoyuan_@localhost ~]$</div>
若仅仅想要将脚本输出保存到文件中,也可直接借助会话窗口的日志抓取功能。
注意,控制台重定向的影响是全局性的,仅适用于比较简单的输出任务。
2.2 print >>重定向
这种方式基于print语句的扩展形式,即"print obj >> expr"。其中,obj为一个file-like(尤其是提供write方法的)对象,为None时对应标准输出(sys.stdout)。expr将被输出到该文件对象中。
示例如下:
memo = cStringIO.StringIO(); serr = sys.stderr; file = open('out.txt', 'w+')
print >>memo, 'StringIO'; print >>serr, 'stderr'; print >>file, 'file'
print >>None, memo.getvalue()
</div>
上述代码执行后,屏显为"serr"和"StringIO"(两行,注意顺序),out.txt文件内写入"file"。
可见,这种方式非常灵活和方便。缺点是不适用于输出语句较多的场景。
2.3 sys.stdout重定向
将一个可写对象(如file-like对象)赋给sys.stdout,可使随后的print语句输出至该对象。重定向结束后,应将sys.stdout恢复最初的缺省值,即标准输出。
简单示例如下:
import sys
savedStdout = sys.stdout #保存标准输出流
with open('out.txt', 'w+') as file:
sys.stdout = file #标准输出重定向至文件
print 'This message is for file!'
sys.stdout = savedStdout #恢复标准输出流
print 'This message is for screen!'
</div>
注意,IDLE中sys.stdout初值为PseudoOutputFile对象,与sys.__stdout__并不相同。为求通用,本例另行定义变量(savedStdout)保存sys.stdout,下文也将作此处理。此外,本例不适用于经由from sys import stdout导入的stdout对象。
以下将自定义多种具有write()方法的file-like对象,以满足不同需求:
class RedirectStdout: #import os, sys, cStringIO
def __init__(self):
self.content = ''
self.savedStdout = sys.stdout
self.memObj, self.fileObj, self.nulObj = None, None, None
#外部的print语句将执行本write()方法,并由当前sys.stdout输出
def write(self, outStr):
#self.content.append(outStr)
self.content += outStr
def toCons(self): #标准输出重定向至控制台
sys.stdout = self.savedStdout #sys.__stdout__
def toMemo(self): #标准输出重定向至内存
self.memObj = cStringIO.StringIO()
sys.stdout = self.memObj
def toFile(self, file='out.txt'): #标准输出重定向至文件
self.fileObj = open(file, 'a+', 1) #改为行缓冲
sys.stdout = self.fileObj
def toMute(self): #抑制输出
self.nulObj = open(os.devnull, 'w')
sys.stdout = self.nulObj
def restore(self):
self.content = ''
if self.memObj.closed != True:
self.memObj.close()
if self.fileObj.closed != True:
self.fileObj.close()
if self.nulObj.closed != True:
self.nulObj.close()
sys.stdout = self.savedStdout #sys.__stdout__
</div>
注意,toFile()方法中,open(name[, mode[, buffering]])调用选择行缓冲(无缓冲会影响性能)。这是为了观察中间写入过程,否则只有调用close()或flush()后输出才会写入文件。内部调用open()方法的缺点是不便于用户定制写文件规则,如模式(覆盖或追加)和缓冲(行或全缓冲)。
重定向效果如下:
redirObj = RedirectStdout() sys.stdout = redirObj #本句会抑制"Let's begin!"输出 print "Let's begin!" #屏显'Hello World!'和'I am xywang.'(两行) redirObj.toCons(); print 'Hello World!'; print 'I am xywang.' #写入'How are you?'和"Can't complain."(两行) redirObj.toFile(); print 'How are you?'; print

