python 2.x 中print >> sys.out ,print 与sys.out.write()的关系

print 会调用 sys.stdout 的 write 方法

以下两行在事实上等价:

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

print >> sys.stdout 相当于把输出重定向到sys.stdout对象( 一般我们使用的时候不加输出定向符“>>”到输出的file对象),默认的sys.stdout对象是控制台,也可以进行改变让它重定向到文件,如:sys.out = open('f.txt','w')

原始的 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

import sys 
temp = sys.stdout
sys.stdout = open('file.txt','w')
print 'hello world'
sys.stdout = temp #恢复默认映射关系
print 'nice'
复制代码
由于在python2中输出默认换行,因此在2.x中若想实现输出不换行,只能直接调用stdout对象的write方法,因为stdout没有end这个符号这一说,输出不会换行,因此如果你想同一样输出多次,在需要输出的字符串对象里面加上"\r",就可以回到行首了。 
sys.stdout.write( "File transfer progress :[%3d] percent complete!\r" % i )
1 # coding=utf-8
2 import sys, os
3 import time
4 for i in range( 100 ):
5     time.sleep( .5 )
6     sys.stdout.write( "File transfer progress :[%3d] percent complete!\r" % i )
7     sys.stdout.flush()
此外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
posted @ 2018-11-21 15:05  SteveSun  阅读(1031)  评论(0编辑  收藏  举报