Reputation: 11259
Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
Upvotes: 2
Views: 420
Reputation: 414199
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
Upvotes: 6
Reputation: 134157
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:
Upvotes: 3