python 标准输出 sys.stdout 重定向
2017-11-18 19:38
555 查看
环境:python2.7
上面这两行是等价的.
上面这两种方法是等价的.
上面这样执行完不会输出到控制台而是写入文件中,如果想恢复,就在重新指定文件对象之前把原始的控制台对象保留下来,向文件中写完之后再把控制台对象找回来,如下
同样的,sys.stderr, sys.stdin 也都可以被重定向到多个地址,但是我感觉用日志模块来搞是不是更方便?总之要了解这种方法,,避免以后看到了不懂!
from:http://www.cnblogs.com/turtle-fly/p/3280519.html
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
相关文章推荐
- Python 标准输出 sys.stdout 重定向
- Python 标准输出 sys.stdout 重定向(转)
- sys.stdout的应用,Python标准输出sys.stdout的重定向
- Python 标准输出 sys.stdout 重定向,将屏幕输出内容输出到文件
- Python 标准输出 sys.stdout 重定向
- Python 标准输出 sys.stdout 重定向
- Python 标准输出 sys.stdout 重定向
- Python第十天 print >> f,和fd.write()的区别 stdout的buffer 标准输入 标准输出 从控制台重定向到文件 标准错误 重定向 输出流和输入流 捕获sys.exit()调用
- python 以标准输出(sys.stdout)为例,看python的标准输入、标准错误输出
- 在python中如何重定向标准输出stdout到文件代码示例
- Python输出标准输出重定向
- 详解python的几种标准输出重定向方式
- Python的sys.stdout、sys.stdin重定向
- python重定向sys.stdin、sys.stdout和sys.stderr
- Python的sys.stdout、sys.stdin重定向
- python重定向sys.stdin、sys.stdout和sys.stderr
- python同时标准输出和重定向到文件保存
- Python标准输出重定向
- python标准输出 标准错误 重定向
- [转载] Python标准输出重定向