python 以標準輸出

stdout詳解.從控制檯重定向到文件

標準輸出(sys.stdout)對應的操做就是print(打印)了,標準輸入(sys.stdin)則對應input(接收輸入)操做,標準錯誤輸出和標準輸出相似也是print(打印)。python

python最基本的操做 - 打印:函數

print 1

其效果是把 1 寫在console(命令行)裏面讓你看。命令行

實際上他的操做能夠理解爲:把console(命令行)做爲一個板子,經過sys.stdout = console指定往console板子上寫東西(console是默認的,也就是說你不修改要往哪兒寫的話,就會默認往這寫),在print 1的時候,就是告訴python,我要寫1,而後python就會去sys.stdout所指定的板子裏,也就是console(命令行)裏寫上 1。(標準錯誤輸出也是一樣的過程,你會發現當程序出錯時,錯誤信息也會打印在console裏面。)指針

其實只要一個對象具備write方法,就能夠被看成「板子」,告訴sys.stdout去哪裏寫。日誌

說道write方法,第一個想到的可能就是文件操做了。code

f=open('log.txt','w')

像上面那樣聲明一個文件對象 f,此文件對象就擁有了write方法,就能夠被用來看成標準輸出和保準錯誤輸出的板子。對象

f=open('log.txt','w')
__console__ = sys.stdout    #把默認的「板子」 - 命令行作個備份,以即可以改回來

sys.stdout = f

print 1

sys.stdout = __console__
print 2

上面的操做,經過sys.stdout = f 指定打印時的板子改爲了 f。因此在使用print的時候,再也不是把1打印在命令行裏,而是寫在了log.txt文件裏面。後面又把板子改爲了命令行,此時print 2就又把2打印到命令行內存

#同時重定向到控制檯和文件字符串

若是咱們但願打印的內容一方面輸出到控制檯,另外一方面輸出到文件做爲日誌保存,那麼該怎麼辦? 將打印的內容保留在內存中,而不是一打印就將 buffer 釋放刷新,那麼放到一個字符串區域中會怎樣?get

a=''
sys.stdout=a
print 'hello'

OK,上述代碼是沒法正常運行的

Traceback (most recent call last):
  File ".\hello.py", line xx, in <module>
    print 'hello'
AttributeError: 'str' object has no attribute 'write'

錯誤很明顯,就是上面強調過的,在嘗試調用 sys.stdout.write() 的時候,發現沒有 write 方法

另外,這裏之因此提示 attribute error 而不是找不到函數等等,我猜測是由於 python 將對象/類的函數指針記錄做爲對象/類的一個屬性來對待,只是保留了函數的入口地址

既然這樣,那麼咱們必須給重定向到的對象實現一個 write 方法:

import sys

class __redirection__:
    
    def __init__(self):
        self.buff=''
        self.__console__=sys.stdout
        
    def write(self, output_stream):
        self.buff+=output_stream
        
    def to_console(self):
        sys.stdout=self.__console__
        print self.buff
    
    def to_file(self, file_path):
        f=open(file_path,'w')
        sys.stdout=f
        print self.buff
        f.close()
    
    def flush(self):
        self.buff=''
        
    def reset(self):
        sys.stdout=self.__console__
        

if __name__=="__main__":
    # redirection
    r_obj=__redirection__()
    sys.stdout=r_obj
    
    # get output stream
    print 'hello'
    print 'there'
    
    # redirect to console
    r_obj.to_console()
    
    # redirect to file
    r_obj.to_file('out.log')
    
    # flush buffer
    r_obj.flush()
    
    # reset
    r_obj.reset()
相關文章
相關標籤/搜索