Python的print輸出重定向舉例分析

本篇內(nèi)容介紹了“Python的print輸出重定向舉例分析”的有關知識,在實際案例的操作過程中,不少人都會遇到這樣的困境,接下來就讓小編帶領大家學習一下如何處理這些情況吧!希望大家仔細閱讀,能夠?qū)W有所成!

成都創(chuàng)新互聯(lián)于2013年成立,先為田林等服務建站,田林等地企業(yè),進行企業(yè)商務咨詢服務。為田林企業(yè)網(wǎng)站制作PC+手機+微官網(wǎng)三網(wǎng)同步一站式服務解決您的所有建站問題。

Python中調(diào)試程序使用最多的是print(),在使用print()打印時事實上是調(diào)用了 sys.stdout.write()。不過print在把內(nèi)容打印到控制臺后,追加了一個換行符(linefeed)。以下例程中,print和sys.stdout.write()是等價的:

sys.stdout.write('Hello World\n')
print('Hello World')

在Python中, sys.stdin、sys.stdout和sys.stderr分別對應解釋器的標準輸入、標準輸出和標準出錯流。在程序啟動時,這些對象的初值由sys.stdin、sys.__stdout__和sys.__stderr__保存,比便于恢復標準流對象。如下所示:

print(sys.stdout) # <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
print(sys.stdin) # <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
print(sys.stderr) # <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>
print(sys.__stdout__) # <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
print(sys.__stdin__) # <_io.TextIOWrapper name='<stdin>' mode='r' encoding='UTF-8'>
print(sys.__stderr__) # <_io.TextIOWrapper name='<stderr>' mode='w' encoding='UTF-8'>

如果我們要把內(nèi)容重定向到文本中去時,該如何操作呢?我們先看下普通的文本對象和標準輸出對象的區(qū)別。如下所示:

print(dir(sys.stdout))
"""
['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', 
'__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', 
'__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', 
'__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
'__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', 
'_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 
'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 
'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 
'write_through', 'writelines']
"""
with open('redirect.txt', 'w') as f:
    print(f) # <_io.TextIOWrapper name='redirect.txt' mode='w' encoding='cp1252'>
    print(dir(f))
    """
    ['_CHUNK_SIZE', '__class__', '__del__', '__delattr__', '__dict__', '__dir__', '__doc__', 
    '__enter__', '__eq__', '__exit__', '__format__', '__ge__', '__getattribute__', '__getstate__', 
    '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__lt__', 
    '__ne__', '__new__', '__next__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', 
    '__sizeof__', '__str__', '__subclasshook__', '_checkClosed', '_checkReadable', '_checkSeekable', 
    '_checkWritable', '_finalizing', 'buffer', 'close', 'closed', 'detach', 'encoding', 'errors', 
    'fileno', 'flush', 'isatty', 'line_buffering', 'mode', 'name', 'newlines', 'read', 'readable', 
    'readline', 'readlines', 'reconfigure', 'seek', 'seekable', 'tell', 'truncate', 'writable', 'write', 
    'write_through', 'writelines']
    """

可見兩者都屬于文件對象,其中所包含的方法也都相同,比如write、read等等。所以,如果把文件對象的引用賦值給sys.stdout,那么print調(diào)用的即為文件對象的write方法,這樣就實現(xiàn)了重定向。其實在之前的Python基礎教程中有跟大家講古。代碼如下所示:

with open('redirect.txt', 'w') as f:
    sys.stdout = f
    print("Hello World")

重定向后,print打印的內(nèi)容就從控制臺搬到了文本上了,如下所示:

Python的print輸出重定向舉例分析

如果只是臨時向文件中打印內(nèi)容,之后仍然會在控制臺上打印的話,應該先將原始的控制臺引用對象保存下來,之后將該引用恢復到sys.stdout中。如下所示:

__console__ = sys.stdout
# redirection start
# ...
# redirection end
sys.stdout = __console__

以上的實現(xiàn)方法并不優(yōu)雅,典型的實現(xiàn)如下所示:

# 臨時把標準輸出重定向到一個文件,然后再恢復正常
with open('redirect.txt', 'w') as f:
    oldstdout = sys.stdout
    sys.stdout = f
    try:
        help(__import__)
    finally:
        sys.stdout = oldstdout
print("Hello World")

Python的print輸出重定向舉例分析

接下來介紹Pyhton上下文管理器redirect_stdout實現(xiàn)重定向的方法。contextlib.redirect_stdout在Python 3.4加入。如下所示:

with open('redirect.txt', 'w') as f:
    with contextlib.redirect_stdout(f):
        help(pow)

Python的print輸出重定向舉例分析

當然,其實redirect_stdout的內(nèi)在實現(xiàn)邏輯也僅是保存控制臺的引用,而后恢復如此而已。于是我們可以實現(xiàn)自己的redirect_stdout上下文管理器。如下所示:

@contextlib.contextmanager
def redirect_stdout(fileobj):
    oldstdout = sys.stdout
    sys.stdout = fileobj
    try:
        yield fileobj
    finally:
        sys.stdout = oldstdout
def redirect4():
    with open('redirect.txt', 'w') as f:
        with redirect_stdout(f):
            help(pow)
    print("Hello World")

“Python的print輸出重定向舉例分析”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關的知識可以關注創(chuàng)新互聯(lián)網(wǎng)站,小編將為大家輸出更多高質(zhì)量的實用文章!

分享題目:Python的print輸出重定向舉例分析
文章起源:http://muchs.cn/article36/jchjsg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)頁設計公司、外貿(mào)建站、網(wǎng)站設計、軟件開發(fā)網(wǎng)站導航、用戶體驗

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

外貿(mào)網(wǎng)站制作