简体   繁体   English

Python 子包导入“没有名为 x 的模块”

[英]Python subpackage import “no module named x”

I'm trying to build a package that has the following structure,我正在尝试构建具有以下结构的 package,

  • __init__.py __init__.py
  • a.py一个.py
  • subpackage分包
    • __init__.py __init__.py
    • b.py b.py

a.py file contains a class from b.py, let say "classX". a.py 文件包含来自 b.py 的 class,比如说“classX”。 So, a.py has the following line at the beginning of file,因此,a.py 在文件开头有以下行,

from subpackage.b import classX

The problem is that, when I try to use this entire package from outside, I get the error "no module named 'b'".问题是,当我尝试从外部使用整个 package 时,我收到错误“没有名为 'b' 的模块”。

How can I fix this problem?我该如何解决这个问题?

Your directory structure should be你的目录结构应该是

package (choose whatever name you want for the high-level package name)
    __init__.py
    a.py
    subpackage
        __init__.py
        b.py

The parent directory of package needs to be in the sys.path list of directories to be searched for resolving imports. package目录需要位于要搜索解析导入的目录的sys.path列表中。 This can be accomplished by having that directory being the current working directory when you invoke whatever program you are running or adding the directory to the PYTHONPATH environment variable or modifying sys.path at runtime before doing your imports.这可以通过在您调用正在运行的任何程序时将该目录作为当前工作目录来实现,或者将该目录添加到PYTHONPATH环境变量或在运行时修改sys.path在执行导入之前。

Then a.py should be either:那么a.py应该是:

from package.subpackage.b import classX

or或者

from .subpackage.b import classX

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

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