您好,欢迎访问一九零五行业门户网

python标准输出重定向方式

一. 背景
在python中,文件对象sys.stdin、sys.stdout和sys.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 $shell或echo $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流。
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
三. 总结
以上就是关于python标准输出的重定向方式的全部内容,希望对学习python的朋友们能有所帮助,如果有疑问欢迎大家留言讨论。
更多python标准输出重定向方式。
其它类似信息

推荐信息