python重定向sys.stdin、sys.stdout和sys.stderr

转自:https://www.cnblogs.com/guyuyuan/p/6885448.html

标准输入、标准输出和错误输出。

标准输入:一般是键盘。stdin对象为解释器提供输入字符流,一般使用raw_input()和input()函数。

例如:让用户输入信息(Python环境为2.x):

复制代码
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 import sys
4 name = raw_input("Please input your name: ")
5 print name
6  
7 # python test.py
8 Please input your name: xiaoming
9 xiaoming
复制代码
复制代码
1 import sys
2 print "Please enter your name: "
3 name = sys.stdin.readline()
4 print name
5  
6 # python b.py
7 Please enter your name:
8 xiaoming
9 xiaoming
复制代码

再例如,a.py文件标准输出作为b.py文件标准输入:

复制代码
 1 # cat a.py
 2 import sys
 3 sys.stdout.write("123456
")
 4 sys.stdout.flush()
 5 # cat b.py
 6 import sys
 7 print sys.stdin.readlines()
 8  
 9 # python a.py | python b.py
10 ['123456
']
复制代码

sys.stdout.write()方法其实就是下面所讲的标准输出,print语句就是调用了这个方法。

标准输出:一般是屏幕。stdout对象接收到print语句产生的输出。

例如:打印一个字符串:

复制代码
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3 import sys
4 print "Hello world!"
5  
6 # python test.py
7 Hello world!
复制代码

sys.stdout是有缓冲区的,比如:

复制代码
1 import sys
2 import time
3 for i in range(5):
4     print i,
5     # sys.stdout.flush()
6     time.sleep(1)
7 # python test.py
8 0 1 2 3 4
复制代码

本是每隔一秒输出一个数字,但现在是循环完才会打印所有结果。如果把sys.stdout.flush()去掉,就会没执行到print就会刷新stdout输出,这对实时输出信息的程序有帮助。

错误输出:一般是错误信息。stderr对象接收出错的信息。

例如:引发一个异常

1 >>> raise Exception, "raise..."
2 Traceback (most recent call last):File "<stdin>", line 1, in <module>
3 Exception: raise...

总结:

 sys.stdout与print

当我们在 Python 中打印对象调用 print obj 时候,事实上是调用了 sys.stdout.write(obj+' ') ;print 将你需要的内容打印到了控制台,然后追加了一个换行符;print 会调用 sys.stdout 的 write 方法

以下两行在事实上等价:

1 sys.stdout.write('hello'+'
') 
2 
3 print 'hello'

sys.stdin与raw_input:

当我们用 raw_input('Input promption: ') 时,事实上是先把提示信息输出,然后捕获输入

以下两组在事实上等价:

1 hi=raw_input('hello? ') 
2 
3 print 'hello? ', #comma to stay in the same line 
4 
5 hi=sys.stdin.readline()[:-1] # -1 to discard the '
' in input stream

从控制台重定向到文件

原始的 sys.stdout 指向控制台

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

复制代码
1 f_handler=open('out.log', 'w') 
2 
3 sys.stdout=f_handler 
4 
5 print 'hello'
6 
7 # this hello can't be viewed on concole 
8 
9 # this hello is in file out.log
复制代码

记住,如果你还想在控制台打印一些东西的话,最好先将原始的控制台对象引用保存下来,向文件中打印之后再恢复 sys.stdout:

复制代码
1 __console__=sys.stdout 
2 
3 # redirection start # 
4 
5 ... 
6 
7 # redirection end 
8 
9 sys.stdout=__console__
复制代码
原文地址:https://www.cnblogs.com/fengff/p/8890111.html