How to test if a module exists?

Rob Williscroft rtw at rtw.me.uk
Sat Nov 6 15:59:46 EDT 2010


Jon Dufresne wrote in 
news:AANLkTikr5euHQPupA3yRid98OaS92ZFHK8U9Lha5YVrv at mail.gmail.com in 
gmane.comp.python.general:

> try:
>     import extension_magic_module
> except ImportError:
>     pass
> else:
>     handle_extension_magic_module()
> 
> 
> However, if the the extension module exists but throws an ImportError,
> due to a bug in the extension this idiom will mask the error and I
> will never see it.

import imp
try:
  m = imp.find_module( "test_1" )
  if m[0]:
    m[0].close()
except ImportError:
  pass
else:
  import test_1

http://docs.python.org/library/imp.html#imp.find_module

Rob.




More information about the Python-list mailing list