Redirecting standard out in a single namespace

Bengt Richter bokr at oz.net
Mon Jan 23 04:26:03 EST 2006


On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <fuzzyman at gmail.com> wrote:

>Hello,
>
>I'm trying to redirect standard out in a single namespace.
>
>I can replace sys.stdout with a custom object - but that affects all
>namespaces.
>
>There will be code running simultaneously that could import sys
>afterwards - so I don't want to make the change in the sys module.
>
>I have an idea to redefine __import__ for the relevant namespace - so
>that an attempt to import sys will return a different module with a
>custom object for stdout. As sys is a builtin module this might not
>work for the print statement, which is what I want to redirect.
>
>I'm not in a position to test my idea until later :
>
>__import = __import__
>def __import__(name):
>    if name == 'sys':
>        return __import('newsys')
>    else:
>        return __import(name)
>
>import sys
>
>Is there another way to shadow the sys module from a single namespace ?
>
It wouldn't be shadowing, but I suppose you could replace sys.stdout with
a custom object whose methods check where they were called from.
Then you could give the object initialization parameters as to which namespace
you want to have the effect in, and/or methods to control the action or turn
it on or off etc. BTW, how about stderr?

Regards,
Bengt Richter



More information about the Python-list mailing list