Redirecting standard out in a single namespace

Fuzzyman fuzzyman at
Mon Jan 23 06:54:30 EST 2006

Bengt Richter wrote:

> On 20 Jan 2006 07:37:15 -0800, "Fuzzyman" <fuzzyman at> 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.
> >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?

I've just tried checking __name__ in my custom stdout object.
Unfortunately __name__ is always the module in which the new stdout
object lives.

In theory I could go up (down?) the stack to the previous frame and
check __name__ there - but it sounds like a hack.

Any other ways of checking where sys.stdout is called from ?

All the best,


> Regards,
> Bengt Richter

More information about the Python-list mailing list