简体   繁体   English

导入与现有模块相同的 package 模块

[英]Import module with same package as existing one

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. /some/dir/mainmodule/some/dir/submodules都不在 pyhton 的库路径上。 Being located in directory /some/dir/mainmodule I want to import all modules ( module.submodule_1 , ..., module.submodule_n ) in directory /some/dir/submodules .位于目录/some/dir/mainmodule我想导入目录/some/dir/submodules中的所有模块( module.submodule_1 ,..., module.submodule_n )。

I tried the following.我尝试了以下。 But I always get ImportError: No module named submodule_1 :但我总是得到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 .问题似乎是 /some/dir/mainmodule 中的module.py/some/dir/mainmodule /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.重新命名module.py或 package 解决了这个问题,但由于这是我正在处理的一些广泛使用的遗留代码,我不知道是否有对这些名称的无证引用。 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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