2

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

3 Answers 3

6
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
3

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:

1
0
x = __import__('a.b.module', fromlist=[''])

Reference

2
  • >>> 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 api video name doc ccb >>> Why mobius gets imported instead of mobius.api ?
    – Nullpoet
    Jun 23, 2010 at 14:12
  • See comment below for answer. Updating my answer now.
    – jhleath
    Jun 23, 2010 at 14:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.