简体   繁体   English

在子模块中导入子模块 - Python

[英]Importing submodule in a submodule - Python

I am trying to import a submodule withing a seperate submodule using python.我正在尝试使用 python 导入一个带有单独子模块的子模块。 Here is my directory structure这是我的目录结构

在此处输入图片说明

I am trying to do this in process_qc.py我试图在 process_qc.py 中做到这一点

from package.database import database

d = database.Database('spark')
print(d.sparkSelect('SHOW DATABASES'))

It gives me error: ModuleNotFoundError: No module named 'package'它给了我错误:ModuleNotFoundError: No module named 'package'

您可以尝试使用相对导入来执行此操作:

from ..database import database

Python does not know where package exists when you use an absolute import.当您使用绝对导入时,Python 不知道package在哪里。 This is because Python first looks in the built-in modules and then at directories listed in sys.path for the requested import.这是因为 Python 首先在内置模块中查找,然后在sys.path列出的目录中sys.path所请求的导入。 If the import is not found, the current working directory is prepended to sys.path .如果未找到导入,当前工作目录将添加到sys.path

To use absolute imports, you should either:要使用绝对导入,您应该:

  1. Execute the script from outside the package directory so that the package directory is discoverable from a path listed in sys.path .package目录外部执行脚本,以便可以从sys.path列出的路径发现package目录。
  2. Add the package directory to your PYTHONPATH :将包目录添加到您的PYTHONPATH
$ export PYTHONPATH=$PYTHONPATH':path/to/package'

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

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