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
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
jfs
Use
fromlist parameter otherwise you get a instead of a.b.module stackoverflow.com/questions/3102252/…x = __import__('a.b.module', fromlist=[''])
2 Comments
Nullpoet
>>> 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 ?
jhleath
See comment below for answer. Updating my answer now.