欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

詳解python的幾種標(biāo)準(zhǔn)輸出重定向方式

 更新時間:2016年08月15日 10:09:26   投稿:daisy  
這篇文章是基于Python2.7版本,介紹常見的幾種標(biāo)準(zhǔn)輸出(stdout)重定向方式。顯然,這些方式也適用于標(biāo)準(zhǔn)錯誤重定向。學(xué)習(xí)python的小伙伴們可以參考借鑒。

一. 背景

在Python中,文件對象sys.stdin、sys.stdoutsys.stderr分別對應(yīng)解釋器的標(biāo)準(zhǔn)輸入、標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)出錯流。在程序啟動時,這些對象的初值由sys.__stdin__sys.__stdout__sys.__stderr__保存,以便用于收尾(finalization)時恢復(fù)標(biāo)準(zhǔn)流對象。

Windows系統(tǒng)中IDLE(Python GUI)由pythonw.exe,該GUI沒有控制臺。因此,IDLE將標(biāo)準(zhǔn)輸出句柄替換為特殊的PseudoOutputFile對象,以便腳本輸出重定向到IDLE終端窗口(Shell)。這可能導(dǎo)致一些奇怪的問題,例如:

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

可以發(fā)現(xiàn),sys.__stdout__sys.stdout取值并不相同。而在普通的Python解釋器下(如通過Windows控制臺)運行上述代碼時,兩者取值相同。

print語句(statement)不以逗號結(jié)尾時,會在輸出字符串尾部自動附加一個換行符(linefeed);否則將一個空格代替附加的換行符。print語句默認(rèn)寫入標(biāo)準(zhǔn)輸出流,也可重定向至文件或其他可寫對象(所有提供write方法的對象)。這樣,就可以使用簡潔的print語句代替笨拙的object.write('hello'+'\n')寫法。

由上可知,在Python中調(diào)用print obj打印對象時,缺省情況下等效于調(diào)用sys.stdout.write(obj+'\n')

示例如下:

>>> import sys
>>> print 'Hello World'
Hello World
>>> sys.stdout.write('Hello World')
Hello World

二. 重定向方式

本節(jié)介紹常用的Python標(biāo)準(zhǔn)輸出重定向方式。這些方法各有優(yōu)劣之處,適用于不同的場景。

2.1 控制臺重定向

最簡單常用的輸出重定向方式是利用控制臺命令。這種重定向由控制臺完成,而與Python本身無關(guān)。

Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通過">"或">>"將輸出重定向。其中,">"表示覆蓋內(nèi)容,">>"表示追加內(nèi)容。類似地,"2>"可重定向標(biāo)準(zhǔn)錯誤。重定向到"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命令提示符中執(zhí)行Python腳本時,命令行無需以"python"開頭,系統(tǒng)會根據(jù)腳本后綴自動調(diào)用Python解釋器。此外,type命令可直接顯示文本文件的內(nèi)容,類似Linux系統(tǒng)的cat命令。

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

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

注意,控制臺重定向的影響是全局性的,僅適用于比較簡單的輸出任務(wù)。

2.2 print >>重定向

這種方式基于print語句的擴展形式,即"print obj >> expr"。其中,obj為一個file-like(尤其是提供write方法的)對象,為None時對應(yīng)標(biāo)準(zhǔn)輸出(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()

上述代碼執(zhí)行后,屏顯為"serr"和"StringIO"(兩行,注意順序),out.txt文件內(nèi)寫入"file"。

可見,這種方式非常靈活和方便。缺點是不適用于輸出語句較多的場景。

2.3 sys.stdout重定向

將一個可寫對象(如file-like對象)賦給sys.stdout,可使隨后的print語句輸出至該對象。重定向結(jié)束后,應(yīng)將sys.stdout恢復(fù)最初的缺省值,即標(biāo)準(zhǔn)輸出。

簡單示例如下:

import sys
savedStdout = sys.stdout #保存標(biāo)準(zhǔn)輸出流
with open('out.txt', 'w+') as file:
  sys.stdout = file #標(biāo)準(zhǔn)輸出重定向至文件
  print 'This message is for file!'

sys.stdout = savedStdout #恢復(fù)標(biāo)準(zhǔn)輸出流
print 'This message is for screen!'

注意,IDLE中sys.stdout初值為PseudoOutputFile對象,與sys.__stdout__并不相同。為求通用,本例另行定義變量(savedStdout)保存sys.stdout,下文也將作此處理。此外,本例不適用于經(jīng)由from sys import stdout導(dǎo)入的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語句將執(zhí)行本write()方法,并由當(dāng)前sys.stdout輸出
  def write(self, outStr):
    #self.content.append(outStr)
    self.content += outStr

  def toCons(self): #標(biāo)準(zhǔn)輸出重定向至控制臺
    sys.stdout = self.savedStdout #sys.__stdout__

  def toMemo(self): #標(biāo)準(zhǔn)輸出重定向至內(nèi)存
    self.memObj = cStringIO.StringIO()
    sys.stdout = self.memObj

  def toFile(self, file='out.txt'): #標(biāo)準(zhǔn)輸出重定向至文件
    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]])調(diào)用選擇行緩沖(無緩沖會影響性能)。這是為了觀察中間寫入過程,否則只有調(diào)用close()flush()后輸出才會寫入文件。內(nèi)部調(diào)用open()方法的缺點是不便于用戶定制寫文件規(guī)則,如模式(覆蓋或追加)和緩沖(行或全緩沖)。

重定向效果如下:

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>'  #無屏顯或?qū)懭?
os.system('echo Never redirect me!')  #控制臺屏顯'Never redirect me!'
redirObj.toMemo(); print 'What a pity!' #無屏顯或?qū)懭?
redirObj.toCons(); print 'Hello?'    #屏顯
redirObj.toFile(); print "Oh, xywang can't hear me" #該串寫入文件
redirObj.restore()

print 'Pop up' #屏顯

可見,執(zhí)行toXXXX()語句后,標(biāo)準(zhǔn)輸出流將被重定向到XXXX。此外,toMute()toMemo()的效果類似,均可抑制輸出。

使用某對象替換sys.stdout時,盡量確保該對象接近文件對象,尤其是涉及第三方庫時(該庫可能使用sys.stdout的其他方法)。此外,本節(jié)替換sys.stdout的代碼實現(xiàn)并不影響由os.popen()、os.system()os.exec*()系列方法所創(chuàng)建進程的標(biāo)準(zhǔn)I/O流。

2.4 上下文管理器(Context Manager)

本節(jié)嚴(yán)格意義上并非新的重定向方式,而是利用Pyhton上下文管理器優(yōu)化上節(jié)的代碼實現(xiàn)。借助于上下文管理器語法,可不必向重定向使用者暴露sys.stdout。

首先考慮輸出抑制,基于上下文管理器語法實現(xiàn)如下:

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內(nèi)嵌塊里的函數(shù)和print語句輸出均被重定向。注意,上述示例不是線程安全的,主要適用于單線程。

當(dāng)函數(shù)被頻繁調(diào)用時,建議使用裝飾器包裝該函數(shù)。這樣,僅需修改該函數(shù)定義,而無需在每次調(diào)用該函數(shù)時使用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的參數(shù)retCache為真,外部調(diào)用func()函數(shù)時將返回該函數(shù)內(nèi)部print輸出的內(nèi)容(可供屏顯);若retCache為假,外部調(diào)用func()函數(shù)時將返回該函數(shù)的返回值(抑制輸出)。

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'

在所有線程中,被裝飾函數(shù)執(zhí)行期間,sys.stdout都會被MuteStdout裝飾器劫持。而且,函數(shù)一經(jīng)裝飾便無法移除裝飾。因此,使用該裝飾器時應(yīng)慎重考慮場景。

接著,考慮創(chuàng)建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'(應(yīng)顯示'FunNoArg')

file.close()

注意FunTwoArg()函數(shù)的定義和調(diào)用與其他函數(shù)的不同,這是兩種等效的語法。此外,RedirectStdout裝飾器的最內(nèi)層函數(shù)wrapper()未使用"functools.wraps(func)"修飾,會丟失被裝飾函數(shù)原有的特殊屬性(如函數(shù)名、文檔字符串等)。

2.5 logging模塊重定向

對于代碼量較大的工程,建議使用logging模塊進行輸出。該模塊是線程安全的,可將日志信息輸出到控制臺、寫入文件、使用TCP/UDP協(xié)議發(fā)送到網(wǎng)絡(luò)等等。

默認(rèn)情況下logging模塊將日志輸出到控制臺(標(biāo)準(zhǔn)出錯),且只顯示大于或等于設(shè)置的日志級別的日志。日志級別由高到低為CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,默認(rèn)級別為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(默認(rèn)為標(biāo)準(zhǔn)錯誤)
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設(shè)置不同的level參數(shù),可將不同的日志內(nèi)容輸入到不同的地方。本例使用在logging模塊內(nèi)置的StreamHandler(和FileHandler),運行后屏幕上顯示:

[INFO  ] ofni
[CRITICAL] lacitirc

out.txt文件內(nèi)容則為:

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

除直接在程序中設(shè)置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

此處共創(chuàng)建三個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文件內(nèi)容則為:

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

三. 總結(jié)

以上就是關(guān)于Python標(biāo)準(zhǔn)輸出的重定向方式的全部內(nèi)容,希望對學(xué)習(xí)python的朋友們能有所幫助,如果有疑問歡迎大家留言討論。

相關(guān)文章

最新評論