Recording messages and print statements in a textfile during program execution.

Heiko Wundram heikowu at ceosg.de
Thu Sep 16 06:55:20 EDT 2004


Am Donnerstag, 16. September 2004 12:36 schrieb Manfred Schwab:
> Recording messages and print statements in a textfile during program
> execution.

Example:

<file name="redirect.py">
import sys

_originalStdout = sys.stdout
_originalStderr = sys.stderr

def redirectTo(stdoutstream,stderrstream=None):
 sys.stdout = stdoutstream
 sys.stderr = stderrstream or stdoutstream

def resetRedirect():
 sys.stdout = _originalStdout
 sys.stderr = _originalStderr
</file>

<file name="example1.py">
from redirect import *

redirectTo(file("example1.log","w"))
print "This is a test logging message."
print "Yet another one."
raise RuntimeError, "and this error will also be logged to the file."
</file>

<file name="example2.py">
from redirect import *

redirectTo(file("example2.log","w"),file("example2.error-log","w"))
print "This will be written to example2.log"
raise RuntimeError, "This error message is written to example2.error-log"
</file>

<file name="example3.py">
from redirect import *
import StringIO

x = StringIO.StringIO()
redirectTo(x)
print "This message will appear in the string buffer."
print "This message will also appear in the string buffer."

# Do something with x.
file("example3.log","w").write(x.uppercase())

# Reset redirection.
resetRedirect()

print "This message will appear on screen."
print "This message too."
raise RuntimeError, "This error will also appear on screen."
</file>

HTH!

Heiko.



More information about the Python-list mailing list