Nullpoet
Nullpoet

Reputation: 11259

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.module'
How can I import it ?

Upvotes: 2

Views: 420

Answers (3)

jhleath
jhleath

Reputation: 804

x = __import__('a.b.module', fromlist=[''])

Reference

Upvotes: 0

jfs
jfs

Reputation: 414199

>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'

Upvotes: 6

Justin Ethier
Justin Ethier

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

Related Questions