look for a module without import it

Fredrik Lundh fredrik at pythonware.com
Fri Jul 14 08:33:31 EDT 2006


Michele Petrazzo wrote:

> I have to know if a module are present on the system, but I don't want
> to import it. Only know if it is present.
>
> I think that a loop on the site-packages directory can do the work, but
> is there another solution?

> more module.py
print "I'M MODULE!"

> python
>>> import imp
>>> imp.find_module("os")
(<open file 'C:\python25\lib\os.py', mode 'U' at 0x00A7E2F0>, 'C:\\python25\\lib\\os.py', ('.py', 
'U', 1))
>>> imp.find_module("sys")
(None, 'sys', ('', '', 6))
>>> imp.find_module("foobar")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named foobar
>>> imp.find_module("module")
(<open file 'module.py', mode 'U' at 0x00A7E2F0>, 'module.py', ('.py', 'U', 1))
>>> import module
I'M MODULE!

</F> 






More information about the Python-list mailing list