Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Python (http://www.programmingforums.org/forum43.html)
-   -   Redirecting Console Output (http://www.programmingforums.org/showthread.php?t=10114)

Sane May 31st, 2006 11:21 PM

Redirecting Console Output
 
I need to redirect all console output (including error messages) to a log file. There are several reasons why I would have to go out of my way to change each print statement to a call to a function. It would be much easier if there's some support in the sys library for just that?

Any helpful info?

hydroxide Jun 1st, 2006 12:12 AM

Quote:

Originally Posted by Sane
I need to redirect all console output (including error messages) to a log file. There are several reasons why I would have to go out of my way to change each print statement to a call to a function. It would be much easier if there's some support in the sys library for just that?

Any helpful info?

It's not a great way of doing things, but you can just set sys.stdout to your logfile:
:

import sys
oldstdout = sys.stdout    # So you can restore later
sys.stdout = file("C:/temp/test.txt", "w")  # Or whatever your logfile is
for i in range(10):
    print "Hello", i
sys.stdout.close()
sys.stdout = oldstdout

An alternative might be to do a find and replace of all instances of "print " to "print>>STDERR,". Then at the top of your module or config file define STDERR as your logfile. If you want to have things print to screen then change STDERR to sys.stderr.

Another alternative would be to import logging and actually log things properly rather than using prints.

-T.

Cerulean Jun 1st, 2006 1:00 PM

You generally do this from the command line. Not sure if this is the same with windows (doubtful) but under Linux (with BASH) you generally do
:

python foo.py > logfile.txt 2>&1
The `2>&1` bit redirects stderr into stdout, and the `> logfile.txt` bit redirects stdout into logfile.txt.
If you're writing to stderr from your Python program then you want to just set sys.stderr to sys.stdout at the top of your source file, which will effectively 'redirect' everything to STDOUT.

megamind5005 Jun 1st, 2006 4:56 PM

The "> file.ex" thing does work in windows as does the "< input.ex" for providing automatic input. Didnt know about the "2>&1" ... where abouts can I find some documentation on it, Cerulean?


All times are GMT -5. The time now is 2:59 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC