howto check does module 'asdf' exist? (is available for import)

Carsten Haese carsten at uniqsys.com
Tue May 22 08:29:42 EDT 2007


On Tue, 2007-05-22 at 00:27 -0700, Asun Friere wrote:
> You can generalise this, but at the expense of a couple of exec
> statements:
> def is_module_available (module) :
>     try :
>         exec('import %s' % module)
>         exec('del %s' % module)
>     except ImportError :
>         return False
>     else :
>         return True

You can save the exec statement by using the built-in __import__
function:

def is_module_available(modulename):
   try: mod = __import__(modulename)
   except ImportError: return False
   else: return True

-- 
Carsten Haese
http://informixdb.sourceforge.net





More information about the Python-list mailing list