Redirecting standard out in a single namespace

Fuzzyman fuzzyman at gmail.com
Mon Jan 23 07:00:40 EST 2006


Bengt Richter wrote:

> 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.
> >[snip..]
> >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?
>

Redirecting stderr is identical in concept to redirecting stdout.

The following in the write method of the custom out object works :

    sys._getframe(1).f_globals['__name__']

sys.stdout.write is *always* called from at least one frame deep in the
stack - so it works.

However the Python docs say of sys._getframe :

    This function should be used for internal and specialized purposes
only.

Might this approach be brittle ?

All the best,


Fuzzyman
http://www.voidspace.org.uk/python/index.shtml

> Regards,
> Bengt Richter




More information about the Python-list mailing list