I want to have the output I get in my IDE window (using MacPython 2.2.2
primarily in Carbon) to be written to a file instead of having to copy the
output and then paste it to a text file myself. How would I go about doing
this?
Mainly I would be using the code to do this with programs that calculate
outputs of large numbers (primes, Fibonacci, etc.) and they sometimes
overflow the buffer and I cannot get back very far to view the beginning.
Make sense? Basically since I am doing this in the IDE window anyway.
Any suggestions?
Thanks!
I'm guessing that you are now "print"-ing the results of your calculations
to the screen, as in:
def fib(n):
a,b = 0,1
while b<n:
print b,
a,b = b,a+b
Instead of printing them to the screen, print them to a file:
def fib(n, resultfile):
a,b = 0,1
while b<n:
print >>resultfile, b,
a,b = b,a+b
fib(2000, open("fibonacci_to_2000.txt",'w'))
You might also want to check the following parts of the manual:
http://www.python.org/doc/current/tut/node9.html#SECTION009200000000000000000
http://www.python.org/doc/current/lib/module-StringIO.html
If you want you can even replace the 'default' standard output (your
screen) with your own file object:
sys.stdout=open("my_stdout.txt",'w')
Does this make sense?
--Irmen
That looks as if it what I was looking for and I thank you for the response.
I will give it a shot.
One more thing, though. Do I need to specify a path to the resultfile that
I will be writing to, or will it just default to the directory that Python
resides in when I execute it?
Eric
"Irmen de Jong" <irmen@-NOSPAM-REMOVETHIS-xs4all.nl> wrote in message
news:3ead7e89$0$49116$e4fe...@news.xs4all.nl...
import sys
outf = open('somefile.txt','w')
sys.stdout = outf
Leave the rest of your program unchagned.
Has the advantage that you can easily change the behavior back and forth by
commenting out the sys.stdout = line.