2013-04-28 106 views
0

說在Python REPL I,分別稱爲os.close012它們是standard input, output and error。我如何重新打開/重新初始化它們?這樣我會在函數或代碼塊的開始處關閉它們,並在返回之前重新打開。如何重新打開文件描述符0,1和2?

PS:Python特有的和通用的細節都將不勝感激。

+0

將它們複製到另一個文件描述符,然後將它們複製回來是否公平? – Xymostech 2013-04-28 15:25:59

+0

@Xymostech我真的問過這個問題來獲得一些內在的(也許太技術)的過程細節。因此,答案可能包括*重複*,但重新開放的部分應該存在,或者可能是重複*是唯一解決方案的原因 – 2013-04-28 15:38:40

回答

2

您無法關閉它們然後重新打開它們,但是您可以複製它們並在完成後恢復以前的值。像這樣的東西;

copy_of_stdin = os.dup(0) // Duplicate stdin to a new descriptor 
copy_of_stdout = os.dup(1) // Duplicate stdout to a new descriptor 
copy_of_stderr = os.dup(2) // Duplicate stderr to a new descriptor 
os.closerange(0,2)   // Close stdin/out/err 

...redirect stdin/out/err at will... 

os.dup2(copy_of_stdin, 0) // Restore stdin 
os.dup2(copy_of_stdout, 1) // Restore stdout 
os.dup2(copy_of_stderr, 2) // Restore stderr 
os.close(copy_of_stdin)  // Close the copies 
os.close(copy_of_stdout) 
os.close(copy_of_stderr)