unexpected from/import statement behaviour

Peter Otten __peter__ at web.de
Wed Aug 27 03:56:57 EDT 2008


nisp wrote:

> Hi all !
> 
> I'm trying to capture stderr of an external module I use in my python
> program. I'm doing this
> by setting up a class in my module overwriting the stderr file object
> method write.
> The external module outputs to stderr this way:
> 
> from sys import std err
> 
> ....
> 
> print >> stderr, "Some text"
> 
> While in my module I use
> 
> import sys
> 
> ..... sys.stderr ... sys.stdout
> 
> Well, as long as I do not change in the external module those from/
> import statements to just
> 
> import sys
> 
> ....
> 
> print >> sys.stderr, "Some text"
> 
> I'm not able to capture its stderr and of course I would like not to
> do this kind of change.
> I've always been convinced of the equivalence of the two ways of using
> the import statement
> but it's clear I'm wrong :-(
> 
> Please, someone can tell me what's going on ?
> 
> Thanks in advance !

A practical approach to complement Diez' link to the explanation:

Instead of modifying the external module you can either redirect stderr
before you import the external module

import sys
sys.stderr = whatever
import external

or monkey-patch:

import sys
import external

sys.stderr = external.sterr = whatever

Peter




More information about the Python-list mailing list