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'
Sign up to request clarification or add additional context in comments.

Comments

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 Comment

Use fromlist parameter otherwise you get a instead of a.b.module stackoverflow.com/questions/3102252/…
0
x = __import__('a.b.module', fromlist=[''])

Reference

2 Comments

>>> 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 ?
See comment below for answer. Updating my answer now.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.