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.
You can create a log file and prepare it for writing. Then create a function:
and then replace your print() function name with write_log()
Python lets you capture and assign sys.stdout - as mentioned - to do this:
A simple way to redirect stdout and stderr using the logging module is here: How do I duplicate sys.stdout to a log file in python?
Putting your own file-like in
sys.stdout
will let you capture the text output viaprint
.Next time, you'll be happier if instead of using
print
statements at all you use thelogging
module from the start. It provides the control you want and you can have it write to stdout while that's still where you want it.Many people here have suggested redirecting stdout. This is an ugly solution. It mutates a global and—what's worse—it mutates it for this one module's use. I would sooner make a regex that changes all
print foo
toprint >>my_file, foo
and setmy_file
to either stdout or an actual file of my choosing.sys.stdout
for the process.os.system
is virtually always inferior to using thesubprocess
module. The latter needn't invoke the shell, doesn't pass signals in a way that usually is unwanted, and can be used in a non-blocking manner.You can redirect replace sys.stdout with any object which has same interface as sys.stdout, in that object's write you can print to terminal and to file too. e.g. see this recipe http://code.activestate.com/recipes/119404-print-hook/