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
2009-02-05 19:30:45
Avoid using exec when you can.
nosklo
2009-02-05 23:46:59
+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
2009-02-05 19:44:22
+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
2009-02-06 20:55:26
To check whether the module is there, you'd need to wrap this in try...except ImportError.
Carl Meyer
2009-02-08 14:56:23