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
hm... is it hard to implement your own print() function and decorator that will log anything that is passed to your print function?
Here is a program that does what you describe:
If you use the built in logging module you can configure your loggers with as many outputs as you need: to file, to databases, to emails, etc. However it sounds like you're mixing print for two different uses: logging (recording program flow for later inspection) and prompts. The real work will be to split out those two uses of 'print' into different functions so you get what you need in each place.
A lot of people replace python's generic sys.stdout and sys.stderr to automatically do stuff to text which is being sent to the console. The real console output always lives in
sys.__stdout__
andsys.__stderr__
(so you don't need to worry about somehow 'losing' it) but if you stick any object with the same methods as a file into the variablessys.stdout
andsys.stderr
you can do whatever you like with the output process.You can add this to your script:
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:To revert to just printing to console, just restore the "backup"