一. 背景
在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 win32Type "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>>>>
可以發現,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二. 重定向方式
本節介紹常用的Python標準輸出重定向方式。這些方法各有優劣之處,適用于不同的場景。
2.1 控制臺重定向
最簡單常用的輸出重定向方式是利用控制臺命令。這種重定向由控制臺完成,而與Python本身無關。
Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通過">"或">>"將輸出重定向。其中,">"表示覆蓋內容,">>"表示追加內容。類似地,"2>"可重定向標準錯誤。重定向到"nul"(Windows)或"/dev/null"(Linux)會抑制輸出,既不屏顯也不存盤。
以Windows命令提示符為例,將Python腳本輸出重定向到文件(為縮短篇幅已刪除命令間空行):
E:/>echo print 'hello' > test.pyE:/>test.py > out.txtE:/>type out.txthelloE:/>test.py >> out.txtE:/>type out.txthellohelloE:/>test.py > nul
注意,在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.txthello[wangxiaoyuan_@localhost ~]$ python -c "print 'world'" >> out.txt[wangxiaoyuan_@localhost ~]$ cat out.txt helloworld[wangxiaoyuan_@localhost ~]$ python -c "print 'I am'" | tee out.txtI am[wangxiaoyuan_@localhost ~]$ python -c "print 'xywang'" | tee -a out.txtxywang[wangxiaoyuan_@localhost ~]$ cat out.txtI amxywang[wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > /dev/null[wangxiaoyuan_@localhost ~]$
若僅僅想要將腳本輸出保存到文件中,也可直接借助會話窗口的日志抓取功能。
注意,控制臺重定向的影響是全局性的,僅適用于比較簡單的輸出任務。
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()上述代碼執行后,屏顯為"serr"和"StringIO"(兩行,注意順序),out.txt文件內寫入"file"。
可見,這種方式非常靈活和方便。缺點是不適用于輸出語句較多的場景。
2.3 sys.stdout重定向
將一個可寫對象(如file-like對象)賦給sys.stdout,可使隨后的print語句輸出至該對象。重定向結束后,應將sys.stdout恢復最初的缺省值,即標準輸出。
簡單示例如下:
import syssavedStdout = 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!'注意,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__
注意,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 "Can't complain."redirObj.toCons(); print "What'up?" #屏顯redirObj.toMute(); print '<Silence>' #無屏顯或寫入os.system('echo Never redirect me!') #控制臺屏顯'Never redirect me!'redirObj.toMemo(); print 'What a pity!' #無屏顯或寫入redirObj.toCons(); print 'Hello?' #屏顯redirObj.toFile(); print "Oh, xywang can't hear me" #該串寫入文件redirObj.restore()print 'Pop up' #屏顯可見,執行toXXXX()語句后,標準輸出流將被重定向到XXXX。此外,toMute()和toMemo()的效果類似,均可抑制輸出。
使用某對象替換sys.stdout時,盡量確保該對象接近文件對象,尤其是涉及第三方庫時(該庫可能使用sys.stdout的其他方法)。此外,本節替換sys.stdout的代碼實現并不影響由os.popen()、os.system()或os.exec*()系列方法所創建進程的標準I/O流。
2.4 上下文管理器(Context Manager)
本節嚴格意義上并非新的重定向方式,而是利用Pyhton上下文管理器優化上節的代碼實現。借助于上下文管理器語法,可不必向重定向使用者暴露sys.stdout。
首先考慮輸出抑制,基于上下文管理器語法實現如下:
import sys, cStringIO, contextlibclass DummyFile: def write(self, outStr): pass@contextlib.contextmanagerdef MuteStdout(): savedStdout = sys.stdout sys.stdout = cStringIO.StringIO() #DummyFile() try: yield except Exception: #捕獲到錯誤時,屏顯被抑制的輸出(該處理并非必需) content, sys.stdout = sys.stdout, savedStdout print content.getvalue()#; raise #finally: sys.stdout = savedStdout
使用示例如下:
with MuteStdout(): print "I'll show up when <raise> is executed!" #不屏顯不寫入 raise #屏顯上句 print "I'm hiding myself somewhere:)" #不屏顯
再考慮更通用的輸出重定向:
import os, sysfrom contextlib import contextmanager@contextmanagerdef RedirectStdout(newStdout): savedStdout, sys.stdout = sys.stdout, newStdout try: yield finally: sys.stdout = savedStdout
使用示例如下:
def Greeting(): print 'Hello, boss!'with open('out.txt', "w+") as file: print "I'm writing to you..." #屏顯 with RedirectStdout(file): print 'I hope this letter finds you well!' #寫入文件 print 'Check your mailbox.' #屏顯with open(os.devnull, "w+") as file, RedirectStdout(file): Greeting() #不屏顯不寫入 print 'I deserve a pay raise:)' #不屏顯不寫入print 'Did you hear what I said?' #屏顯可見,with內嵌塊里的函數和print語句輸出均被重定向。注意,上述示例不是線程安全的,主要適用于單線程。
當函數被頻繁調用時,建議使用裝飾器包裝該函數。這樣,僅需修改該函數定義,而無需在每次調用該函數時使用with語句包裹。示例如下:
import sys, cStringIO, functoolsdef MuteStdout(retCache=False): def decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): savedStdout = sys.stdout sys.stdout = cStringIO.StringIO() try: ret = func(*args, **kwargs) if retCache == True: ret = sys.stdout.getvalue().strip() finally: sys.stdout = savedStdout return ret return wrapper return decorator
若裝飾器MuteStdout的參數retCache為真,外部調用func()函數時將返回該函數內部print輸出的內容(可供屏顯);若retCache為假,外部調用func()函數時將返回該函數的返回值(抑制輸出)。
MuteStdout裝飾器使用示例如下:
@MuteStdout(True)def Exclaim(): print 'I am proud of myself!'@MuteStdout()def Mumble(): print 'I lack confidence...'; return 'sad'print Exclaim(), Exclaim.__name__ #屏顯'I am proud of myself! Exclaim'print Mumble(), Mumble.__name__ #屏顯'sad Mumble'
在所有線程中,被裝飾函數執行期間,sys.stdout都會被MuteStdout裝飾器劫持。而且,函數一經裝飾便無法移除裝飾。因此,使用該裝飾器時應慎重考慮場景。
接著,考慮創建RedirectStdout裝飾器:
def RedirectStdout(newStdout=sys.stdout): def decorator(func): def wrapper(*args,**kwargs): savedStdout, sys.stdout = sys.stdout, newStdout try: return func(*args, **kwargs) finally: sys.stdout = savedStdout return wrapper return decorator
使用示例如下:
file = open('out.txt', "w+")@RedirectStdout(file)def FunNoArg(): print 'No argument.'@RedirectStdout(file)def FunOneArg(a): print 'One argument:', adef FunTwoArg(a, b): print 'Two arguments: %s, %s' %(a,b)FunNoArg() #寫文件'No argument.'FunOneArg(1984) #寫文件'One argument: 1984'RedirectStdout()(FunTwoArg)(10,29) #屏顯'Two arguments: 10, 29'print FunNoArg.__name__ #屏顯'wrapper'(應顯示'FunNoArg')file.close()注意FunTwoArg()函數的定義和調用與其他函數的不同,這是兩種等效的語法。此外,RedirectStdout裝飾器的最內層函數wrapper()未使用"functools.wraps(func)"修飾,會丟失被裝飾函數原有的特殊屬性(如函數名、文檔字符串等)。
2.5 logging模塊重定向
對于代碼量較大的工程,建議使用logging模塊進行輸出。該模塊是線程安全的,可將日志信息輸出到控制臺、寫入文件、使用TCP/UDP協議發送到網絡等等。
默認情況下logging模塊將日志輸出到控制臺(標準出錯),且只顯示大于或等于設置的日志級別的日志。日志級別由高到低為CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,默認級別為WARNING。
以下示例將日志信息分別輸出到控制臺和寫入文件:
import logginglogging.basicConfig(level = logging.DEBUG, format = '%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)s', datefmt = '%Y-%m-%d(%a)%H:%M:%S', filename = 'out.txt', filemode = 'w') #將大于或等于INFO級別的日志信息輸出到StreamHandler(默認為標準錯誤)console = logging.StreamHandler()console.setLevel(logging.INFO) formatter = logging.Formatter('[%(levelname)-8s] %(message)s') #屏顯實時查看,無需時間console.setFormatter(formatter)logging.getLogger().addHandler(console)logging.debug('gubed'); logging.info('ofni'); logging.critical('lacitirc')通過對多個handler設置不同的level參數,可將不同的日志內容輸入到不同的地方。本例使用在logging模塊內置的StreamHandler(和FileHandler),運行后屏幕上顯示:
[INFO ] ofni[CRITICAL] lacitirc
out.txt文件內容則為:
2016-05-13(Fri)17:10:53 [DEBUG] at test.py,25: gubed2016-05-13(Fri)17:10:53 [INFO] at test.py,25: ofni2016-05-13(Fri)17:10:53 [CRITICAL] at test.py,25: lacitirc
除直接在程序中設置Logger、Handler、Formatter等外,還可將這些信息寫入配置文件。示例如下:
#logger.conf###############Logger###############[loggers]keys=root,Logger2F,Logger2CF[logger_root]level=DEBUGhandlers=hWholeConsole[logger_Logger2F]handlers=hWholeFilequalname=Logger2Fpropagate=0[logger_Logger2CF]handlers=hPartialConsole,hPartialFilequalname=Logger2CFpropagate=0###############Handler###############[handlers]keys=hWholeConsole,hPartialConsole,hWholeFile,hPartialFile[handler_hWholeConsole]class=StreamHandlerlevel=DEBUGformatter=simpFormatterargs=(sys.stdout,)[handler_hPartialConsole]class=StreamHandlerlevel=INFOformatter=simpFormatterargs=(sys.stderr,)[handler_hWholeFile]class=FileHandlerlevel=DEBUGformatter=timeFormatterargs=('out.txt', 'a')[handler_hPartialFile]class=FileHandlerlevel=WARNINGformatter=timeFormatterargs=('out.txt', 'w')###############Formatter###############[formatters]keys=simpFormatter,timeFormatter[formatter_simpFormatter]format=[%(levelname)s] at %(filename)s,%(lineno)d: %(message)s[formatter_timeFormatter]format=%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)sdatefmt=%Y-%m-%d(%a)%H:%M:%S此處共創建三個Logger:root,將所有日志輸出至控制臺;Logger2F,將所有日志寫入文件;Logger2CF,將級別大于或等于INFO的日志輸出至控制臺,將級別大于或等于WARNING的日志寫入文件。
程序以如下方式解析配置文件和重定向輸出:
import logging, logging.configlogging.config.fileConfig("logger.conf")logger = logging.getLogger("Logger2CF")logger.debug('gubed'); logger.info('ofni'); logger.warn('nraw')logger.error('rorre'); logger.critical('lacitirc')logger1 = logging.getLogger("Logger2F")logger1.debug('GUBED'); logger1.critical('LACITIRC')logger2 = logging.getLogger()logger2.debug('gUbEd'); logger2.critical('lAcItIrC')運行后屏幕上顯示:
[INFO] at test.py,7: ofni[WARNING] at test.py,7: nraw[ERROR] at test.py,8: rorre[CRITICAL] at test.py,8: lacitirc[DEBUG] at test.py,14: gUbEd[CRITICAL] at test.py,14: lAcItIrC
out.txt文件內容則為:
2016-05-13(Fri)20:31:21 [WARNING] at test.py,7: nraw2016-05-13(Fri)20:31:21 [ERROR] at test.py,8: rorre2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,8: lacitirc2016-05-13(Fri)20:31:21 [DEBUG] at test.py,11: GUBED2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,11: LACITIRC
三. 總結
以上就是關于Python標準輸出的重定向方式的全部內容,希望對學習python的朋友們能有所幫助,如果有疑問歡迎大家留言討論。
新聞熱點
疑難解答
圖片精選