I have a long python script that uses print statements often, I was wondering if it was possible to add some code that would log all of the print statements into a text file or something like that. I still want all of the print statements to go to the command line as the user gets prompted throughout the program. If possible logging the user's input would be beneficial as well.
I found this which somewhat answers my question but makes it where the "print" statement no longer prints to the command line
Redirect Python 'print' output to Logger
You can add this to your script:
import sys
sys.stdout = open('logfile', 'w')
This will make the print statements write to logfile
.
If you want the option of printing to stdout
and a file, you can try this:
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f = open('logfile', 'w')
backup = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "hello world" # this should appear in stdout and in file
To revert to just printing to console, just restore the "backup"
sys.stdout = backup
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With