I have the following directory structure:
/some/dir
┣ mainmodule
┃ ┣ __init__.py
┃ ┗ module.py
┗ submodules
┣ __init__.py
┗ module
┣ __init__.py
┣ submodule_1.py
┣ ...
┗ submodule_n.py
Both /some/dir/mainmodule
and /some/dir/submodules
are not on pyhton's library path. Being located in directory /some/dir/mainmodule
I want to import all modules ( module.submodule_1
, ..., module.submodule_n
) in directory /some/dir/submodules
.
I tried the following. But I always get ImportError: No module named submodule_1
:
>>> import sys
>>> sys.path.append("/some/dir/submodules")
>>> import module.submodule_1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named submodule_1
>>>
The problem seems to be that module.py
in /some/dir/mainmodule
has the same name as the first package of the modules in /some/dir/submodules
. Renaiming module.py
or the package solves this issues, but as this is some widely used legacy code I'm working on, I don't know if there are undocumented references to these names. Thus I'm looking for a way to solve this without renaming any files.
use the following line.
sys.path.insert(0, '/some/dir/submodules')
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.