views:

864

answers:

3

I am developing my stuff in python. In this process I encountered a situation where I have a string called "import django". And I want to validate this string. Which means, I want to check whether the module mentioned('django' in this case) is in the python-path. How can I do it?

A: 

I doub't that it's safe, but it's the most naïve solution:

try:
     exec('import django')
except ImportError:
    print('no django')
SilentGhost
Avoid using exec when you can.
nosklo
+13  A: 

My previous answer was wrong -- i didn't think to test my code. This actually works, though: look at the imp module.

To just check for the module's importability in the current sys.path:

try:
    imp.find_module('django', sys.path)
except ImportError:
    print "Boo! no django for you!"
Yoni Samlan
+1 that is the way to do it.
nosklo
Maddy
+1  A: 

If a module's name is available as string you can import it using the built-in __import__ function.

module = __import__("module name", {}, {}, [], -1)

For example,

os = __import__("os", {}, {}, [], -1)
Akbar ibrahim
To check whether the module is there, you'd need to wrap this in try...except ImportError.
Carl Meyer