通俗的来说,sys.stdout的功能类似与C++里面的文件输出功能fPRintf。
接下来直接入正题,让我们来看代码:
>>> import sys>>> temp=sys.stdout>>> sys.stdout=open('E://pythonCode//1.txt','w') #注意是双//>>> print 1,2,3 #1.txt中增加了这三个数字>>> sys.stdout.close() #关闭,有点类似fclose()
假若我们close而不进行输出恢复,看看会有什么结果:
>>> print 1,2,3Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> print 1,2,3ValueError: I/O Operation on closed file
所以我们需要将sys.stdout进行恢复:
>>> sys.stdout=temp>>> print 1,2,31 2 3
顺便说一下,sys.stdout.flush() 可以让数据被立即输出,因为默认情况下,sys.stdout是被缓冲的。
类似的用法还有:
sys.stdin,sys.stderr.
新闻热点
疑难解答