Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
views:
80answers:
3
+2
A:
You can use the build-in __import__
function. For example:
import sys
myconfigfile = sys.argv[1]
try:
config = __import__(myconfigfile)
for i in config.__dict__:
print i
except ImportError:
print "Unable to import configuration file %s" % (myconfigfile,)
For more information, see:
Justin Ethier
2010-06-23 14:00:21
Use `fromlist` parameter otherwise you get `a` instead of `a.b.module` http://stackoverflow.com/questions/3102252/python-how-to-import-a-module-if-i-have-its-path-as-a-string/3102318#3102318
J.F. Sebastian
2010-06-23 14:05:26
>>> n =__import__('mobius.api')>>> n<module 'mobius' from '/home/rhiwale/Desktop/nfsrepo/rohit/mobius/../mobius/__init__.pyc'>>>> >>> for i in n.__dict__:... print i... settings__builtins__docs__file__polls__package____path__apivideo__name____doc__ccb>>> Why mobius gets imported instead of mobius.api ?
Rohit
2010-06-23 14:12:47
+4
A:
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
J.F. Sebastian
2010-06-23 14:04:22