Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?
>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With