Need your help
Thomas Rachel
nutznetz-0c1b6768-bfa9-48d5-a470-7603bd3aa915 at spamschutz.glglgl.de
Thu Apr 28 09:17:33 EDT 2011
Am 28.04.2011 13:14, schrieb Chris Rebert:
> import a, b, sys
> def c():
> orig_stdout = sys.stdout
> sys.stdout = open('my_log_file.log', 'w')
> a.a()
> b.b()
> sys.stdout.close()
> sys.stdout = orig_stdout
>
>
> Someone may have written a with-statement context manager that
> abstracts away the swapping.
@contextlib.contextmanager
def swap_stdout(target):
orig_stdout = sys.stdout
sys.stdout = target
try:
yield target
finally:
sys.stdout = orig_stdout
In this case, I can use all kinds of files (open() files, StringIO
objects etc.), and can re-use them if necessary, in order to
prepend/append data.
Closing can happen additionally, if the user wants.
Thomas
More information about the Python-list
mailing list