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

1

2 Answers 2

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()
$
Sign up to request clarification or add additional context in comments.

1 Comment

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"
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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.