0

I have a python script that currently outputs a bunch of text to stdout (the terminal). It looks something like:

print "ABC"
print "CD"
print "QR"
methodCallToOtherCodeThatAlsoPrints()
# A bunch of other print lines...

Right now all of this output just goes to stdout; however, I want the output to be written to a file in addition to writing to the terminal. What is the best way to do this? Ideally I don't want to have to change all of the print statements (to another method call for instance), and I don't have access to some of the code is called to do the printing.

I was thinking, is there someway I can redirect print output to both stdout AND a file?

5gon12eder
  • 24,280
  • 5
  • 45
  • 92
Nosrettap
  • 10,940
  • 23
  • 85
  • 140
  • 3
    This question looks similar: http://stackoverflow.com/questions/14906764/how-to-redirect-stdout-to-file-and-console-with-scripting. There is an answer from Amith Koujalgi that looks like it would work for you. – MikeTheReader Oct 03 '14 at 18:36

1 Answers1

0

open a file and write your string in it:

 with open('my_file' , 'w') as f:
     f.write('your_string')

and if you want to redirect your output to a file use > in terminal after invoke the .py file :

$~ python my_file.py > save_file.txt
Mazdak
  • 105,000
  • 18
  • 159
  • 188
  • 1
    I think OP wants the program to behave as if invoked as `python program.py | tee logfile`. – 5gon12eder Oct 03 '14 at 18:39
  • Create a method that does f.write and print and use search and replace to change the current method to this new one. – eri0o Oct 03 '14 at 19:08