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


標准輸入、標准輸出和錯誤輸出。

標准輸入:一般是鍵盤。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\n")
 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\n']

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+'\n') ;print 將你需要的內容打印到了控制台,然后追加了一個換行符;print 會調用 sys.stdout 的 write 方法

以下兩行在事實上等價:

1 sys.stdout.write('hello'+'\n') 
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 '\n' 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__

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM