开发者

writing Python shell output to file

开发者 https://www.devze.com 2023-04-12 12:12 出处:网络
Very simple question. I am using the IDLE Python shell to run my Python scripts. I use the following type of structure

Very simple question. I am using the IDLE Python shell to run my Python scripts. I use the following type of structure

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

Is there a s开发者_StackOverflow社区imple way of outputting the results to a file? Something like

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

Thanks


$ 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!

NOTE: Changing these objects doesn’t affect the standard I/O streams of processes executed by os.popen(), os.system() or the exec*() family of functions in the os module.
So

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


So sayeth the documentation:

Standard output is defined as the file object named stdout in the built-in module sys.

So you can change stdout like so:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号