4

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

daviddesancho
  • 427
  • 1
  • 7
  • 20
  • 1
    possible duplicate of [Parsing a stdout in Python](http://stackoverflow.com/questions/2101426/parsing-a-stdout-in-python) – crashmstr Oct 11 '11 at 16:03

2 Answers2

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!

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()
$
Lelouch Lamperouge
  • 8,171
  • 8
  • 49
  • 60
  • Should the line `sys.displayhook(stdout)` be `sys.displayhook(sys.stdout)`? When I try to run that line I get "NameError: name 'stdout' is not defined" – mayaPapaya Feb 03 '20 at 22:11
4

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")
Kevin
  • 74,910
  • 12
  • 133
  • 166