简体   繁体   English

使用子模块时的 Python 导入问题

[英]Python Import issue when using submodule

I have a directory structure as shown below:我有一个如下所示的目录结构:

--root
    --common
        util.py
    --submodule
        --common
            util.py
        --code
            a.py
        run.py
    main.py

a.py一个.py

from common.util import test_config

main.py主文件

import submodule.a

a.py is importing some code from common module of the submodule. a.py 正在从子模块的公共模块中导入一些代码。 I have added this submodule in root project.我在根项目中添加了这个子模块。 the submodule itself works fine when run independently.子模块本身在独立运行时工作正常。

When I import a.py in main.py it starts to pick up code from root projects common code instead of the submodule project.当我在 main.py 中导入 a.py 时,它开始从根项目公共代码而不是子模块项目中获取代码。

ImportError: cannot import name 'test_config'

I have tried adding sys.path in a.py to force import submodule code but it is not working.我尝试在 a.py 中添加 sys.path 以强制导入子模块代码,但它不起作用。

a.py一个.py

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

from common.util import test_config

Any help is appreciated任何帮助表示赞赏

Your code in a.py should either use a relative import:您在a.py中的代码应该使用相对导入:

from .common.util import test_config

...or a full import path: ...或完整的导入路径:

from submodule.common.util import test_config

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

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