python sys中的stdin,stdout,stderr
阿新 • • 發佈:2018-12-04
- #testing stdout
- >>> print 'Hello World!' #該語句會在標準輸出的螢幕上列印 Hello World!
- Hello World!
- #等價於:
- >>> import sys
- >>> sys.stdout.write('Hello World!\n')
- Hello World!
- import sys
- print 'Please enter your name:',
- name=sys.stdin.readline()[:-1] #輸入等同於input
- print 'Hi,%s!' % name
內部邏輯實現-----重定向
Python提供了一個StringIO模組來完成這個設想,比如:
- >>> from StringIO import StringIO
- >>> import sys
- >>> buf=StringIO()
- >>> temp=sys.stdout #重定向前儲存stdout
- >>> sys.stdout=buf #將stdout重定向到buff物件
- >>> print 825,'python',0,666 # print會在要列印的資訊後面加上一個硬回車
- >>> sys.stdout=temp #恢復stdout
- >>> buf.getvalue() # print會在要列印的資訊後面加上一個硬回車,因此最後有一個'\n'
- '825 python 0 666\n'