简体   繁体   中英

How to import module dynamically in python with importlib?

In python 3.6.2 I am trying to import a module with importlib . I am able to import the module directly as:

from scripts import config_A_2

but when trying with importlib as follows

module = importlib.import_module('config_A_2', 'scripts')

I get an error

 File "/usr/local/Cellar/python3/3.6.2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 978, in _gcd_import
  File "<frozen importlib._bootstrap>", line 961, in _find_and_load
  File "<frozen importlib._bootstrap>", line 948, in _find_and_load_unlocked    
ModuleNotFoundError: No module named 'config_A_2'

Maybe I am using importlib in a wrong way?

Info: Its a Mac...

You can use a relative import:

importlib.import_module('.config_A_2', 'scripts')

Or an absolute one:

importlib.import_module('scripts.config_A_2', 'scripts')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM