Python : How to import a module if I have its path as a string?
Lets say I have path to a module in a string module_to_be_imported = 'a.b.mo开发者_开发问答dule'
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:
- Python Documentation
- Python.org - [Python Wpg] Import a module using a string
x = __import__('a.b.module', fromlist=[''])
Reference
精彩评论