Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

import

Lets say I have path to a module in a string module_to_be_imported = 'a.b.module'
How can I import it ?

like image 815
Nullpoet Avatar asked Feb 05 '26 18:02

Nullpoet


2 Answers

>>> m = __import__('xml.sax')
>>> m.__name__
'xml'
>>> m = __import__('xml.sax', fromlist=[''])
>>> m.__name__
'xml.sax'
like image 198
jfs Avatar answered Feb 07 '26 09:02

jfs


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
like image 44
Justin Ethier Avatar answered Feb 07 '26 08:02

Justin Ethier



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!