开发者

Python : How to import a module if I have its path as a string?

开发者 https://www.devze.com 2023-01-04 06:52 出处:网络
Lets say I have path to a module in a string module_to_be_imported = \'a.b.mo开发者_开发问答dule\'

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

0

精彩评论

暂无评论...
验证码 换一张
取 消