Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

writing Python shell output to file

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 simple way of outputting the results to a file? Something like

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

Thanks

like image 226
ricoamor Avatar asked Oct 16 '25 14:10

ricoamor


1 Answers

$ 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()
$
like image 185
Lelouch Lamperouge Avatar answered Oct 18 '25 03:10

Lelouch Lamperouge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!