Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redirect prints to log file

Okay. I have completed my first python program.It has around 1000 lines of code. During development I placed plenty of print statements before running a command using os.system() say something like,

print "running command",cmd
os.system(cmd)

Now I have completed the program. I thought about commenting them but redirecting all these unnecessary print (i can't remove all print statements - since some provide useful info for user) into a log file will be more useful? Any tricks or tips.

like image 274
webminal.org Avatar asked Oct 09 '22 13:10

webminal.org


People also ask

How do I print a log file?

You print logs from the Viewer. Select File > View..., or type view logfilename from the command line to load the log into the Viewer, and then right-click on the Viewer and select Print.


1 Answers

Python lets you capture and assign sys.stdout - as mentioned - to do this:

import sys
old_stdout = sys.stdout

log_file = open("message.log","w")

sys.stdout = log_file

print "this will be written to message.log"

sys.stdout = old_stdout

log_file.close()
like image 67
Michael Avatar answered Oct 20 '22 15:10

Michael