您的位置:首页 > 编程语言 > Python开发

python重定向

2013-12-12 18:03 141 查看
1)原始的 sys.stdout 指向控制台

如果把文件的对象的引用赋给 sys.stdout,那么 print 调用的就是文件对象的 write 方法

f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'
this hello can't be viewed on concole
this hello is in file out.log


记住,如果你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印之后再恢复 saveout=sys.stdout

redirection start
...
redirection end
sys.stdout=saveout


2)重定向 stderr 以完全相同的方式进行,只要把 sys.stdout 改为 sys.stderr。

向标准错误写入错误信息是很常见的,所以有一种较快的语法可以立刻导出信息。

print >> sys.stderr, 'entering function'


在这里,你可以将单个 print 语句重定向到 stderr 而且不用影响后面的 print 语句。

同时重定向到控制台和文件

如果我们希望打印的内容一方面输出到控制台,另一方面输出到文件作为日志保存,那么该怎么办?

将打印的内容保留在内存中,而不是一打印就将 buffer 释放刷新,那么放到一个字符串区域中会怎样?

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


上述代码是无法正常运行的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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: