将Python Shell输出写入文件
这是个很简单的问题。我正在使用IDLE Python环境来运行我的Python脚本。我使用的结构是这样的:
import sys
sys.argv = ['','fileinp']
execfile('mypythonscript.py')
有没有简单的方法可以把结果输出到一个文件里?类似于:
execfile('mypythonscript.py') > 'output.dat'
谢谢
2 个回答
4
文档是这么说的:
标准输出被定义为在内置模块sys中名为stdout的文件对象。
所以你可以这样改变stdout:
import sys
sys.stdout = open("output.dat", "w")
5
$ 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!
>>> import os
>>> os.system("./x")
1 #<-- output from ./x
0 #<-- ./x's return code
>>> quit()
$
注意: 修改这些对象不会影响通过 os.popen()、os.system() 或 os 模块中的 exec*() 系列函数执行的进程的标准输入输出流。
所以