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.
-
try this sys.path.append(0, "/some/dir/submodules")Kabali– Kabali2019年11月22日 10:14:16 +00:00Commented Nov 22, 2019 at 10:14
1 Answer 1
use the following line.
sys.path.insert(0, '/some/dir/submodules')