Redirecting standard out in a single namespace
fuzzyman at gmail.com
Tue Jan 24 06:40:58 EST 2006
Bengt Richter wrote:
> >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.
> Yes, that's about what I had in mind, not being able to think of an alternative
> (other than the obvious one of using something other than print in the module
> where you want to redirect, either by hand or by effective source rewrite one way
> or another to translate print statments into e.g. myprint('the', 'print', 'args') or such.
> You could do source preprocessing or translating at the AST level, or you could do byte code munging.
> Nothing too nice.
> >However the Python docs say of sys._getframe :
> > This function should be used for internal and specialized purposes
> >Might this approach be brittle ?
> In what sense? I guess it ought to work for the version it's defined for, but the advice is there.
> Maybe we can get something more specific from the author of the above doc snippet ;-)
``inspect.currentframe`` has no such warning. The equivalent would then
I guess unless the implementation of Python changes that will continue
to work. :-)
> Bengt Richter
More information about the Python-list