Python的sys.stdout、sys.stdin重定向
2017-04-22 09:42
435 查看
sys.stdout 与 print
当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+'\n')print 将你需要的内容打印到了控制台,然后追加了一个换行符
print 会调用 sys.stdout 的 write 方法
以下两行在事实上等价:
sys.stdout.write('hello'+'\n')
print 'hello'
sys.stdin 与 raw_input
当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入以下两组在事实上等价:
hi=raw_input('hello? ')
print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream
从控制台重定向到文件
原始的 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
记住,如果你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印之后再恢复 sys.stdout
__console__=sys.stdout
# redirection start #
...
# redirection end
sys.stdout=__console__
相关文章推荐
- python重定向sys.stdin、sys.stdout和sys.stderr
- Python的sys.stdout、sys.stdin重定向
- Python的sys.stdout、sys.stdin重定向
- python重定向sys.stdin、sys.stdout和sys.stderr
- Python的sys.stdout、sys.stdin重定向
- python的sys.stdout重定向
- python 打印重定向:stdin,stdout,stderr
- #小练习 重定向与sys.stdout对象 分类: python 小练习 2013-11-05 16:10 437人阅读 评论(0) 收藏
- python之sys.stdout、sys.stdin
- Python 标准输出 sys.stdout 重定向,将屏幕输出内容输出到文件
- sys.stdout的应用,Python标准输出sys.stdout的重定向
- Python 标准输出 sys.stdout 重定向
- Python 标准输出 sys.stdout 重定向
- python3 sys.stdout 方法,sys.exit方法,sys.stdin 方法
- Python 标准输出 sys.stdout 重定向
- python的sys.stdout重定向(转)
- Python 标准输出 sys.stdout 重定向
- Python 标准输出 sys.stdout 重定向(转)
- Python第十天 print >> f,和fd.write()的区别 stdout的buffer 标准输入 标准输出 从控制台重定向到文件 标准错误 重定向 输出流和输入流 捕获sys.exit()调用
- python的sys.stdout重定向