unexpected from/import statement behaviour

Diez B. Roggisch deets at nospam.web.de
Wed Aug 27 08:43:27 EDT 2008


nisp wrote:

> On Aug 27, 9:56 am, Peter Otten <__pete... at web.de> wrote:
>> 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
> 
> Hi all !
> 
> Thanks first of all ! I read the interesting Diez's link but something
> still remains to me unclear, on the other hand it's clear the my
> problem is concentrated there and on symbols.
> Here is what I'm trying to do
> 
> HelloWorld.py: this is a real simplification of my external module
> though still reflecting its structure (commented out is the version
> that, let's say, works)
> 
> from sys import stderr

This is your problem. You create a HelloWorld.stderr-alias to the object
bound to sys.stderr. Rebinding the latter won't affect the former. That is
precisely what the link I gave you explains.

The short answer to the whole issue is: dont' use the from-import syntax
until you really know what you are doing. Or not at all.

Diez



More information about the Python-list mailing list