Python標准輸出重定向


Python標准輸出重定向

標簽: Python stdout 重定向


聲明

本文基於Python2.7版本,介紹常見的幾種標准輸出(stdout)重定向方式。顯然,這些方式也適用於標准錯誤重定向。
本文同時也發布於作業部落,視覺效果略有不同。

一. 背景知識

在Python中,文件對象sys.stdinsys.stdoutsys.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>
>>> 

可以發現,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.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

注意,在Windows命令提示符中執行Python腳本時,命令行無需以"python"開頭,系統會根據腳本后綴自動調用Python解釋器。此外,type命令可直接顯示文本文件的內容,類似Linux系統的cat命令。

Linux Shell中執行Python腳本時,命令行應以"python"開頭。除">"或">>"重定向外,還可使用tee命令。該命令可將內容同時輸出到終端屏幕和(多個)文件中,"-a"選項表示追加寫入,否則覆蓋寫入。示例如下(echo $SHELLecho $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 ~]$ 

若僅僅想要將腳本輸出保存到文件中,也可直接借助會話窗口的日志抓取功能。

注意,控制台重定向的影響是全局性的,僅適用於比較簡單的輸出任務。

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 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!'

注意,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流。這些涉及底層控制,其重定向方式可參考"Redirecting all kinds of stdout in Python"一文。

2.4 上下文管理器(Context Manager)

本節嚴格意義上並非新的重定向方式,而是利用Pyhton上下文管理器優化上節的代碼實現。借助於上下文管理器語法,可不必向重定向使用者暴露sys.stdout。

首先考慮輸出抑制,基於上下文管理器語法實現如下:

import sys, cStringIO, contextlib
class DummyFile:
    def write(self, outStr): pass

@contextlib.contextmanager
def 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, sys
from contextlib import contextmanager
@contextmanager
def 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, functools
def 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:', a

def 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 logging
logging.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: gubed
2016-05-13(Fri)17:10:53 [INFO] at test.py,25: ofni
2016-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=DEBUG
handlers=hWholeConsole

[logger_Logger2F]
handlers=hWholeFile
qualname=Logger2F
propagate=0

[logger_Logger2CF]
handlers=hPartialConsole,hPartialFile
qualname=Logger2CF
propagate=0

###############Handler###############
[handlers]
keys=hWholeConsole,hPartialConsole,hWholeFile,hPartialFile

[handler_hWholeConsole]
class=StreamHandler
level=DEBUG
formatter=simpFormatter
args=(sys.stdout,)

[handler_hPartialConsole]
class=StreamHandler
level=INFO
formatter=simpFormatter
args=(sys.stderr,)

[handler_hWholeFile]
class=FileHandler
level=DEBUG
formatter=timeFormatter
args=('out.txt', 'a')

[handler_hPartialFile]
class=FileHandler
level=WARNING
formatter=timeFormatter
args=('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)s
datefmt=%Y-%m-%d(%a)%H:%M:%S

此處共創建三個Logger:root,將所有日志輸出至控制台;Logger2F,將所有日志寫入文件;Logger2CF,將級別大於或等於INFO的日志輸出至控制台,將級別大於或等於WARNING的日志寫入文件。

程序以如下方式解析配置文件和重定向輸出:

import logging, logging.config

logging.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: nraw
2016-05-13(Fri)20:31:21 [ERROR] at test.py,8: rorre
2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,8: lacitirc
2016-05-13(Fri)20:31:21 [DEBUG] at test.py,11: GUBED
2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,11: LACITIRC

三. 參考資料

本文主要參考以下資料(包括但不限於):


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM