2011-10-11 170 views
2

非常簡單的問題。我正在使用IDLE Python shell來運行我的Python腳本。我使用以下類型的結構將Python shell輸出寫入文件

import sys 
sys.argv = ['','fileinp'] 
execfile('mypythonscript.py') 

是否有一種將結果輸出到文件的簡單方法?喜歡的東西

execfile('mypythonscript.py') > 'output.dat' 

感謝

+1

[在Python解析標準輸出]的可能重複(http://stackoverflow.com/questions/2101426/parsing-a-stdout-in-python) – crashmstr

回答

3
$ python 
Python 2.6.5 (r265:79063, Apr 16 2010, 13:57:41) 
[GCC 4.4.3] on linux2 

>>> import sys 
>>> sys.displayhook(stdout) 
<open file '<stdout>', mode 'w' at 0x7f8d3197a150> 
>>> x=open('myFile','w') 
>>> sys.displayhook(x) 
<open file 'myFile', mode 'w' at 0x7fb729060c00> 
>>> sys.stdout=x 
>>> print 'changed stdout!' 
>>> x.close() 
$ cat myFile 
changed stdout! 

注意:更改這些對象不會影響標準I/O由操作系統執行的過程流。 popen(),os.system()或os模塊中的exec *()系列函數。
所以

>>> import os 
>>> os.system("./x") 
1 #<-- output from ./x 
0 #<-- ./x's return code 
>>> quit() 
$ 
3

所以sayeth文檔:

標準輸出定義爲內置模塊SYS名爲stdout文件對象。

所以你可以改變標準輸出,就像這樣:

import sys 
sys.stdout = open("output.dat", "w") 
+1

這似乎與IDLE很好地工作但不是IPython – ricoamor