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

python 标准输出 sys.stdout 重定向

2017-11-18 19:38 555 查看
环境:python2.7

1.sys.stdout 和 print 关系

调用 python 打印对象 print obj的时候,事实上其实是都用了 sys.stdout.write(obj+’\n’),也就是说 print 调用了 sys.stdout 的 write 方法.

sys.stdout.write('hello'+'\n')
print 'hello'


上面这两行是等价的.

2.sys.stdin 和 raw_input

使用 raw.input(‘Input promption:’)的时候实际上是先把提示信息输出,然后捕获输入信息.

hi = raw_input('hello?')

print 'hello?',
hi = sys.stdin.readline()[:-1]


上面这两种方法是等价的.

3.从控制台到文件

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

f_handler = open('out.log','w')
sys.stdout = f_handler
print 'hello'


上面这样执行完不会输出到控制台而是写入文件中,如果想恢复,就在重新指定文件对象之前把原始的控制台对象保留下来,向文件中写完之后再把控制台对象找回来,如下

__console__=sys.stdout

f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'

sys.stdout=__console__


4.同事重定向到控制台和文件

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


同样的,sys.stderr, sys.stdin 也都可以被重定向到多个地址,但是我感觉用日志模块来搞是不是更方便?总之要了解这种方法,,避免以后看到了不懂!

from:http://www.cnblogs.com/turtle-fly/p/3280519.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: