Python的sys.stdout、sys.stdin重定向

sys.stdout 與 print

當我們在 Python 中打印對象調用 print obj 時候,事實上是調用了 sys.stdout.write(obj+'\n')

print 將你需要的內容打印到了控制檯,然後追加了一個換行符

print 會調用 sys.stdout 的 write 方法

以下兩行在事實上等價:

sys.stdout.write('hello'+'\n') 

print 'hello'

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

從控制檯重定向到文件

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

__console__=sys.stdout 

# redirection start # 

... 

# redirection end 

sys.stdout=__console__

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章