How to test if a module exists?

Jean-Michel Pichavant jeanmichel at sequans.com
Tue Nov 9 06:02:22 EST 2010


Jon Dufresne wrote:
> On Sat, Nov 6, 2010 at 1:52 PM, Roy Smith <roy at panix.com> wrote:
>   
>> import sys
>> try:
>>    import xx
>> except ImportError:
>>    tb = sys.exc_traceback
>>    while tb:
>>        print tb
>>        tb = tb.tb_next
>>
>>     
>
> I went ahead and implemented this and it now works. I even uncovered a
> bug I wasn't previously seeing because now the program was failing
> early! :)
>
> I hope there isn't a hidden naivete in using this pattern.
>
> Thanks,
> Jon
>   
try:
   ....:        import xx
   ....: except ImportError:
   ....:        tb = sys.exc_traceback
   ....:    while tb:
   ....:            print tb
   ....:        tb = tb.tb_next
   ....:
<traceback object at 0x9981464>


I don't see how it solves your problem. It does not test if a module 
exists, nor does it handles missing or flawed modules differently.

JM




More information about the Python-list mailing list