[关闭]
@cloverwang 2016-05-13T12:56:51.000000Z 字数 11364 阅读 5306

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)。这可能导致一些奇怪的问题,例如:

  1. Python 2.7.11 (v2.7.11:6d1b6a68f775, Dec 5 2015, 20:32:19) [MSC v.1500 32 bit (Intel)] on win32
  2. Type "copyright", "credits" or "license()" for more information.
  3. >>> import sys
  4. >>> for fd in (sys.stdin, sys.stdout, sys.stderr): print fd
  5. <idlelib.PyShell.PseudoInputFile object at 0x0177C910>
  6. <idlelib.PyShell.PseudoOutputFile object at 0x0177C970>
  7. <idlelib.PyShell.PseudoOutputFile object at 0x017852B0>
  8. >>> for fd in (sys.__stdin__, sys.__stdout__, sys.__stderr__): print fd
  9. <open file '<stdin>', mode 'r' at 0x00FED020>
  10. <open file '<stdout>', mode 'w' at 0x00FED078>
  11. <open file '<stderr>', mode 'w' at 0x00FED0D0>
  12. >>>

可以发现,sys.__stdout__sys.stdout取值并不相同。而在普通的Python解释器下(如通过Windows控制台)运行上述代码时,两者取值相同。

print语句(statement)不以逗号结尾时,会在输出字符串尾部自动附加一个换行符(linefeed);否则将一个空格代替附加的换行符。print语句默认写入标准输出流,也可重定向至文件或其他可写对象(所有提供write方法的对象)。这样,就可以使用简洁的print语句代替笨拙的object.write('hello'+'\n')写法。

由上可知,在Python中调用print obj打印对象时,缺省情况下等效于调用sys.stdout.write(obj+'\n')。示例如下:

  1. >>> import sys
  2. >>> print 'Hello World'
  3. Hello World
  4. >>> sys.stdout.write('Hello World')
  5. Hello World

二. 重定向方式

本节介绍常用的Python标准输出重定向方式。这些方法各有优劣之处,适用于不同的场景。

2.1 控制台重定向

最简单常用的输出重定向方式是利用控制台命令。这种重定向由控制台完成,而与Python本身无关。

Windows命令提示符(cmd.exe)和Linux Shell(bash等)均通过">"或">>"将输出重定向。其中,">"表示覆盖内容,">>"表示追加内容。类似地,"2>"可重定向标准错误。重定向到"nul"(Windows)或"/dev/null"(Linux)会抑制输出,既不屏显也不存盘。

以Windows命令提示符为例,将Python脚本输出重定向到文件(为缩短篇幅已删除命令间空行):

  1. E:\>echo print 'hello' > test.py
  2. E:\>test.py > out.txt
  3. E:\>type out.txt
  4. hello
  5. E:\>test.py >> out.txt
  6. E:\>type out.txt
  7. hello
  8. hello
  9. E:\>test.py > nul

注意,在Windows命令提示符中执行Python脚本时,命令行无需以"python"开头,系统会根据脚本后缀自动调用Python解释器。此外,type命令可直接显示文本文件的内容,类似Linux系统的cat命令。

Linux Shell中执行Python脚本时,命令行应以"python"开头。除">"或">>"重定向外,还可使用tee命令。该命令可将内容同时输出到终端屏幕和(多个)文件中,"-a"选项表示追加写入,否则覆盖写入。示例如下(echo $SHELLecho $0显示当前所使用的Shell):

  1. [wangxiaoyuan_@localhost ~]$ echo $SHELL
  2. /bin/bash
  3. [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'"
  4. hello
  5. [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > out.txt
  6. [wangxiaoyuan_@localhost ~]$ cat out.txt
  7. hello
  8. [wangxiaoyuan_@localhost ~]$ python -c "print 'world'" >> out.txt
  9. [wangxiaoyuan_@localhost ~]$ cat out.txt
  10. hello
  11. world
  12. [wangxiaoyuan_@localhost ~]$ python -c "print 'I am'" | tee out.txt
  13. I am
  14. [wangxiaoyuan_@localhost ~]$ python -c "print 'xywang'" | tee -a out.txt
  15. xywang
  16. [wangxiaoyuan_@localhost ~]$ cat out.txt
  17. I am
  18. xywang
  19. [wangxiaoyuan_@localhost ~]$ python -c "print 'hello'" > /dev/null
  20. [wangxiaoyuan_@localhost ~]$

若仅仅想要将脚本输出保存到文件中,也可直接借助会话窗口的日志抓取功能。

注意,控制台重定向的影响是全局性的,仅适用于比较简单的输出任务。

2.2 print >>重定向

这种方式基于print语句的扩展形式,即"print obj >> expr"。其中,obj为一个file-like(尤其是提供write方法的)对象,为None时对应标准输出(sys.stdout)。expr将被输出到该文件对象中。示例如下:

  1. memo = cStringIO.StringIO(); serr = sys.stderr; file = open('out.txt', 'w+')
  2. print >>memo, 'StringIO'; print >>serr, 'stderr'; print >>file, 'file'
  3. print >>None, memo.getvalue()

上述代码执行后,屏显为"serr"和"StringIO"(两行,注意顺序),out.txt文件内写入"file"。

可见,这种方式非常灵活和方便。缺点是不适用于输出语句较多的场景。

2.3 sys.stdout重定向

将一个可写对象(如file-like对象)赋给sys.stdout,可使随后的print语句输出至该对象。重定向结束后,应将sys.stdout恢复最初的缺省值,即标准输出。

简单示例如下:

  1. import sys
  2. savedStdout = sys.stdout #保存标准输出流
  3. with open('out.txt', 'w+') as file:
  4. sys.stdout = file #标准输出重定向至文件
  5. print 'This message is for file!'
  6. sys.stdout = savedStdout #恢复标准输出流
  7. print 'This message is for screen!'

注意,IDLE中sys.stdout初值为PseudoOutputFile对象,与sys.__stdout__并不相同。为求通用,本例另行定义变量(savedStdout)保存sys.stdout,下文也将作此处理。此外,本例不适用于经由from sys import stdout导入的stdout对象。

以下将自定义多种具有write()方法的file-like对象,以满足不同需求:

  1. class RedirectStdout: #import os, sys, cStringIO
  2. def __init__(self):
  3. self.content = ''
  4. self.savedStdout = sys.stdout
  5. self.memObj, self.fileObj, self.nulObj = None, None, None
  6. #外部的print语句将执行本write()方法,并由当前sys.stdout输出
  7. def write(self, outStr):
  8. #self.content.append(outStr)
  9. self.content += outStr
  10. def toCons(self): #标准输出重定向至控制台
  11. sys.stdout = self.savedStdout #sys.__stdout__
  12. def toMemo(self): #标准输出重定向至内存
  13. self.memObj = cStringIO.StringIO()
  14. sys.stdout = self.memObj
  15. def toFile(self, file='out.txt'): #标准输出重定向至文件
  16. self.fileObj = open(file, 'a+', 1) #改为行缓冲
  17. sys.stdout = self.fileObj
  18. def toMute(self): #抑制输出
  19. self.nulObj = open(os.devnull, 'w')
  20. sys.stdout = self.nulObj
  21. def restore(self):
  22. self.content = ''
  23. if self.memObj.closed != True:
  24. self.memObj.close()
  25. if self.fileObj.closed != True:
  26. self.fileObj.close()
  27. if self.nulObj.closed != True:
  28. self.nulObj.close()
  29. sys.stdout = self.savedStdout #sys.__stdout__

注意,toFile()方法中,open(name[, mode[, buffering]])调用选择行缓冲(无缓冲会影响性能)。这是为了观察中间写入过程,否则只有调用close()或flush()后输出才会写入文件。内部调用open()方法的缺点是不便于用户定制写文件规则,如模式(覆盖或追加)和缓冲(行或全缓冲)。

重定向效果如下:

  1. redirObj = RedirectStdout()
  2. sys.stdout = redirObj #本句会抑制"Let's begin!"输出
  3. print "Let's begin!"
  4. #屏显'Hello World!'和'I am xywang.'(两行)
  5. redirObj.toCons(); print 'Hello World!'; print 'I am xywang.'
  6. #写入'How are you?'和"Can't complain."(两行)
  7. redirObj.toFile(); print 'How are you?'; print "Can't complain."
  8. redirObj.toCons(); print "What'up?" #屏显
  9. redirObj.toMute(); print '<Silence>' #无屏显或写入
  10. os.system('echo Never redirect me!') #控制台屏显'Never redirect me!'
  11. redirObj.toMemo(); print 'What a pity!' #无屏显或写入
  12. redirObj.toCons(); print 'Hello?' #屏显
  13. redirObj.toFile(); print "Oh, xywang can't hear me" #该串写入文件
  14. redirObj.restore()
  15. 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。

首先考虑输出抑制,基于上下文管理器语法实现如下:

  1. import sys, cStringIO, contextlib
  2. class DummyFile:
  3. def write(self, outStr): pass
  4. @contextlib.contextmanager
  5. def MuteStdout():
  6. savedStdout = sys.stdout
  7. sys.stdout = cStringIO.StringIO() #DummyFile()
  8. try:
  9. yield
  10. except Exception: #捕获到错误时,屏显被抑制的输出(该处理并非必需)
  11. content, sys.stdout = sys.stdout, savedStdout
  12. print content.getvalue()#; raise
  13. #finally:
  14. sys.stdout = savedStdout

使用示例如下:

  1. with MuteStdout():
  2. print "I'll show up when <raise> is executed!" #不屏显不写入
  3. raise #屏显上句
  4. print "I'm hiding myself somewhere:)" #不屏显

再考虑更通用的输出重定向:

  1. import os, sys
  2. from contextlib import contextmanager
  3. @contextmanager
  4. def RedirectStdout(newStdout):
  5. savedStdout, sys.stdout = sys.stdout, newStdout
  6. try:
  7. yield
  8. finally:
  9. sys.stdout = savedStdout

使用示例如下:

  1. def Greeting(): print 'Hello, boss!'
  2. with open('out.txt', "w+") as file:
  3. print "I'm writing to you..." #屏显
  4. with RedirectStdout(file):
  5. print 'I hope this letter finds you well!' #写入文件
  6. print 'Check your mailbox.' #屏显
  7. with open(os.devnull, "w+") as file, RedirectStdout(file):
  8. Greeting() #不屏显不写入
  9. print 'I deserve a pay raise:)' #不屏显不写入
  10. print 'Did you hear what I said?' #屏显

可见,with内嵌块里的函数和print语句输出均被重定向。注意,上述示例不是线程安全的,主要适用于单线程。

当函数被频繁调用时,建议使用装饰器包装该函数。这样,仅需修改该函数定义,而无需在每次调用该函数时使用with语句包裹。示例如下:

  1. import sys, cStringIO, functools
  2. def MuteStdout(retCache=False):
  3. def decorator(func):
  4. @functools.wraps(func)
  5. def wrapper(*args, **kwargs):
  6. savedStdout = sys.stdout
  7. sys.stdout = cStringIO.StringIO()
  8. try:
  9. ret = func(*args, **kwargs)
  10. if retCache == True:
  11. ret = sys.stdout.getvalue().strip()
  12. finally:
  13. sys.stdout = savedStdout
  14. return ret
  15. return wrapper
  16. return decorator

若装饰器MuteStdout的参数retCache为真,外部调用func()函数时将返回该函数内部print输出的内容(可供屏显);若retCache为假,外部调用func()函数时将返回该函数的返回值(抑制输出)。

MuteStdout装饰器使用示例如下:

  1. @MuteStdout(True)
  2. def Exclaim(): print 'I am proud of myself!'
  3. @MuteStdout()
  4. def Mumble(): print 'I lack confidence...'; return 'sad'
  5. print Exclaim(), Exclaim.__name__ #屏显'I am proud of myself! Exclaim'
  6. print Mumble(), Mumble.__name__ #屏显'sad Mumble'

在所有线程中,被装饰函数执行期间,sys.stdout都会被MuteStdout装饰器劫持。而且,函数一经装饰便无法移除装饰。因此,使用该装饰器时应慎重考虑场景。

接着,考虑创建RedirectStdout装饰器:

  1. def RedirectStdout(newStdout=sys.stdout):
  2. def decorator(func):
  3. def wrapper(*args,**kwargs):
  4. savedStdout, sys.stdout = sys.stdout, newStdout
  5. try:
  6. return func(*args, **kwargs)
  7. finally:
  8. sys.stdout = savedStdout
  9. return wrapper
  10. return decorator

使用示例如下:

  1. file = open('out.txt', "w+")
  2. @RedirectStdout(file)
  3. def FunNoArg(): print 'No argument.'
  4. @RedirectStdout(file)
  5. def FunOneArg(a): print 'One argument:', a
  6. def FunTwoArg(a, b): print 'Two arguments: %s, %s' %(a,b)
  7. FunNoArg() #写文件'No argument.'
  8. FunOneArg(1984) #写文件'One argument: 1984'
  9. RedirectStdout()(FunTwoArg)(10,29) #屏显'Two arguments: 10, 29'
  10. print FunNoArg.__name__ #屏显'wrapper'(应显示'FunNoArg')
  11. file.close()

注意FunTwoArg()函数的定义和调用与其他函数的不同,这是两种等效的语法。此外,RedirectStdout装饰器的最内层函数wrapper()未使用"functools.wraps(func)"修饰,会丢失被装饰函数原有的特殊属性(如函数名、文档字符串等)。

2.5 logging模块重定向

对于代码量较大的工程,建议使用logging模块进行输出。该模块是线程安全的,可将日志信息输出到控制台、写入文件、使用TCP/UDP协议发送到网络等等。

默认情况下logging模块将日志输出到控制台(标准出错),且只显示大于或等于设置的日志级别的日志。日志级别由高到低为CRITICAL > ERROR > WARNING > INFO > DEBUG > NOTSET,默认级别为WARNING。

以下示例将日志信息分别输出到控制台和写入文件:

  1. import logging
  2. logging.basicConfig(level = logging.DEBUG,
  3. format = '%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)s',
  4. datefmt = '%Y-%m-%d(%a)%H:%M:%S',
  5. filename = 'out.txt',
  6. filemode = 'w')
  7. #将大于或等于INFO级别的日志信息输出到StreamHandler(默认为标准错误)
  8. console = logging.StreamHandler()
  9. console.setLevel(logging.INFO)
  10. formatter = logging.Formatter('[%(levelname)-8s] %(message)s') #屏显实时查看,无需时间
  11. console.setFormatter(formatter)
  12. logging.getLogger().addHandler(console)
  13. logging.debug('gubed'); logging.info('ofni'); logging.critical('lacitirc')

通过对多个handler设置不同的level参数,可将不同的日志内容输入到不同的地方。本例使用在logging模块内置的StreamHandler(和FileHandler),运行后屏幕上显示:

  1. [INFO ] ofni
  2. [CRITICAL] lacitirc

out.txt文件内容则为:

  1. 2016-05-13(Fri)17:10:53 [DEBUG] at test.py,25: gubed
  2. 2016-05-13(Fri)17:10:53 [INFO] at test.py,25: ofni
  3. 2016-05-13(Fri)17:10:53 [CRITICAL] at test.py,25: lacitirc

除直接在程序中设置Logger、Handler、Formatter等外,还可将这些信息写入配置文件。示例如下:

  1. #logger.conf
  2. ###############Logger###############
  3. [loggers]
  4. keys=root,Logger2F,Logger2CF
  5. [logger_root]
  6. level=DEBUG
  7. handlers=hWholeConsole
  8. [logger_Logger2F]
  9. handlers=hWholeFile
  10. qualname=Logger2F
  11. propagate=0
  12. [logger_Logger2CF]
  13. handlers=hPartialConsole,hPartialFile
  14. qualname=Logger2CF
  15. propagate=0
  16. ###############Handler###############
  17. [handlers]
  18. keys=hWholeConsole,hPartialConsole,hWholeFile,hPartialFile
  19. [handler_hWholeConsole]
  20. class=StreamHandler
  21. level=DEBUG
  22. formatter=simpFormatter
  23. args=(sys.stdout,)
  24. [handler_hPartialConsole]
  25. class=StreamHandler
  26. level=INFO
  27. formatter=simpFormatter
  28. args=(sys.stderr,)
  29. [handler_hWholeFile]
  30. class=FileHandler
  31. level=DEBUG
  32. formatter=timeFormatter
  33. args=('out.txt', 'a')
  34. [handler_hPartialFile]
  35. class=FileHandler
  36. level=WARNING
  37. formatter=timeFormatter
  38. args=('out.txt', 'w')
  39. ###############Formatter###############
  40. [formatters]
  41. keys=simpFormatter,timeFormatter
  42. [formatter_simpFormatter]
  43. format=[%(levelname)s] at %(filename)s,%(lineno)d: %(message)s
  44. [formatter_timeFormatter]
  45. format=%(asctime)s [%(levelname)s] at %(filename)s,%(lineno)d: %(message)s
  46. datefmt=%Y-%m-%d(%a)%H:%M:%S

此处共创建三个Logger:root,将所有日志输出至控制台;Logger2F,将所有日志写入文件;Logger2CF,将级别大于或等于INFO的日志输出至控制台,将级别大于或等于WARNING的日志写入文件。

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

  1. import logging, logging.config
  2. logging.config.fileConfig("logger.conf")
  3. logger = logging.getLogger("Logger2CF")
  4. logger.debug('gubed'); logger.info('ofni'); logger.warn('nraw')
  5. logger.error('rorre'); logger.critical('lacitirc')
  6. logger1 = logging.getLogger("Logger2F")
  7. logger1.debug('GUBED'); logger1.critical('LACITIRC')
  8. logger2 = logging.getLogger()
  9. logger2.debug('gUbEd'); logger2.critical('lAcItIrC')

运行后屏幕上显示:

  1. [INFO] at test.py,7: ofni
  2. [WARNING] at test.py,7: nraw
  3. [ERROR] at test.py,8: rorre
  4. [CRITICAL] at test.py,8: lacitirc
  5. [DEBUG] at test.py,14: gUbEd
  6. [CRITICAL] at test.py,14: lAcItIrC

out.txt文件内容则为:

  1. 2016-05-13(Fri)20:31:21 [WARNING] at test.py,7: nraw
  2. 2016-05-13(Fri)20:31:21 [ERROR] at test.py,8: rorre
  3. 2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,8: lacitirc
  4. 2016-05-13(Fri)20:31:21 [DEBUG] at test.py,11: GUBED
  5. 2016-05-13(Fri)20:31:21 [CRITICAL] at test.py,11: LACITIRC

三. 参考资料

本文主要参考以下资料(包括但不限于):
- Redirecting all kinds of stdout in Python
- Redirect stdout to a file in Python?
- Silence the stdout of a function in Python without trashing sys.stdout and restoring each function call

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注