Self Modifying Python? How can I redirect all print statements within a function without touching sys.stdout?

Posted by Fake Name on Stack Overflow See other posts from Stack Overflow or by Fake Name
Published on 2011-01-01T10:04:11Z Indexed on 2011/01/01 10:54 UTC
Read the original article Hit count: 120

Filed under:
|

I have a situation where I am attempting to port some big, complex python routines to a threaded environment.

I want to be able to, on a per-call basis, redirect the output from the function's print statement somewhere else (a logging.Logger to be specific).

I really don't want to modify the source for the code I am compiling, because I need to maintain backwards compatibility with other software that calls these modules (which is single threaded, and captures output by simply grabbing everything written to sys.stdout).

I know the best option is to do some rewriting, but I really don't have a choice here.

Edit -

Alternatively, is there any way I can override the local definition of print to point to a different function?

I could then define the local print = system print unless overwritten by a kwarg, and would only involve modify a few lines at the beginning of each routine.

© Stack Overflow or respective owner

Related posts about python

Related posts about python-2.6