tags:

views:

80

answers:

3

Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?

+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
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
A: 
x = __import__('a.b.module', fromlist=[''])

Reference

huntaub
>>> 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
See comment below for answer. Updating my answer now.
huntaub
+4  A: 
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
J.F. Sebastian