views:

119

answers:

6

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.

+1  A: 

Putting your own file-like in sys.stdout will let you capture the text output via print.

Ignacio Vazquez-Abrams
This is true but awful and shouldn't be used.
Mike Graham
+8  A: 

You should take a look at python logging module

RC
+1 for the logging module. Gives you wayyyy more control than print statements.
Brendan Abel
+1  A: 

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

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()
Michael
You can also do -- sys.stdout = sys.__stdout__ -- instead of using old_stdout.
Brendan Abel
nice, thanks. losing reference to stdout would be nasty
Michael
This is a messy hack, but certainly possible. If you **do** use it, reset `sys.stdout` to its original value in the `finally` block of a `try/finally`.
Mike Graham
@007brendan, that assumes that `sys.stdout` *starts* as `sys.__stdout__`. That isn't a great assumption, someone else could be redirecting `sys.stdout` for a purpose like this or for a more sane use, like a system where a *whole app's* stdout really shouldn't be `sys.__stdout__`.
Mike Graham
+1  A: 

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/

Anurag Uniyal
Though applicable, that recipe is stylistically, semantically, and conceptually awful.
Mike Graham
@Mike Graham, hey i wrote that 8 years ago :), anyway why is that so awful ?
Anurag Uniyal
@Anurag Uniyal, I would avoid using something like that if I could possibly do so for a couple reasons. It changes a global value (`sys.stdout`) for local use and may have accidental, far-off, unexpected effects (this is the reason people avoid using global state). When it's done, it restores the value to `sys.__stdout__`, which may and may not be what `sys.stdout` started as depending on if someone else was doing this sort of trick. It does not have a usage such that an unexpected exception won't leave `sys.stdout` stuck at an unwanted value later.
Mike Graham
@Anurag Uniyal, That being said, I'm sorry to have been uncivil. Though I honestly believe the best solution will not use this kind of technique, I was unduly harsh in my criticism.
Mike Graham
@Mike Graham that is fine, criticism is good, and that hook is hack to divert all the prints of app if need be, in practical situation I have used it on some old apps which have print littered all around
Anurag Uniyal
+1  A: 

A simple way to redirect stdout and stderr using the logging module is here: http://stackoverflow.com/questions/616645/how-do-i-duplicate-sys-stdout-to-a-log-file-in-python/2216517#2216517

blokeley
That solution is disgusting and not even entirely applicable (in that it writes to stdout *and* a file; OP only wants to write to a file.)
Mike Graham
Please could you explain why this is "disgusting"? I know redirecting stdout is a bad idea but sometimes it's worth doing: this week I did it to run django on a server overnight for testing, and django's runserver command prints to stdout.Also, please test your opinion before posting because the solution in question does _not_ write to stdout. I have just tested it again.
blokeley
This is disgusting because it uses globals. This means that when you read `print foo` it doesn't do what you expect it to without reading where the global was changed, which might not even be in the same file as the print statement. It's unmodular because multiple things can't all do this sanely. You even acknowledge that it's a bad idea. When something should be printed to stdout but you want to redirect it, there are tools for this (like `>` on the shell); when something should be written somewhere other than stdout, you should make your code write there instead.
Mike Graham
I apologize about my statement about the code writing to a file and stdout. I was looking at a different solution in the same thread as you linked. My mistake.
Mike Graham
Apology accepted. Thanks for the clarification. I agree one should avoid messing with globals. I have updated my original post to point out that the logging module should be used directly wherever possible. This is what I always intended but didn't say it explicitly until now.
blokeley
+1  A: 
  • Next time, you'll be happier if instead of using print statements at all you use the logging 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 to print >>my_file, foo and set my_file to either stdout or an actual file of my choosing.

    • If you have any other parts of the application that actually depend on writing to stdout (or ever will in the future but you don't know it yet), this breaks them. Even if you don't, it makes reading your module look like it does one thing when it actually does another if you missed one little line up top.
    • Chevron print is pretty ugly, but not nearly as ugly as temporarily changing sys.stdout for the process.
    • Very technically speaking, a regex replacement isn't capable of doing this right (for example, it could make false positives if you are inside of a multiline string literal). However, it's apt to work, just keep an eye on it.
  • os.system is virtually always inferior to using the subprocess 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.

Mike Graham