简体   繁体   English

如何正确导入需要另一个模块运行的模块?

[英]how to properly import a module which need another module to run?

I met an import error called no module named XX.我遇到了一个名为no module named XX. my project file is organized as follows:我的项目文件组织如下:

-------A.py
          |
          B-----__init__.py        wrote: from .C import C
                        |
                        C.py
                        |​
                        D -----__init__.py           wrote: from .E import E
                                         |
                                         E.py

In A.py, I need to import class C from C.py.在 A.py 中,我需要从 C.py 导入 class C。 but class C needs to use class E(in E.py)to run但是 class C 需要使用 class E(in E.py)来运行

In A.py, I wrote import B.C在 A.py 中,我写了import B.C

In C.py, I wrote import DE在 C.py 中,我写了import DE

when I run the test in A.py, it gives the error: No module named 'D' But if I test C.py, there is no problem at all.当我在 A.py 中运行测试时,它给出了错误: No module named 'D'但是如果我测试 C.py,则完全没有问题。

Can anyone tell me why and how to fix it?谁能告诉我为什么以及如何解决它?

When you try to run A.py , it fails because the Python interpreter (the program that runs your Python script) cannot find the D package.当您尝试运行A.py时,它会失败,因为 Python 解释器(运行 Python 脚本的程序)找不到D ZEFE90A8E604A7C840E88D03A67F6B7D8。

When you run C.py , however, the interpreter does find the D package.但是,当您运行C.py时,解释器确实找到了D package。 This is because the script you are running ( C.py ) is located in the same directory/folder as the D package.这是因为您正在运行的脚本 ( C.py ) 与D package 位于同一目录/文件夹中。

Detailed explanation found in the Python Docs : Python Docs中的详细解释:

When a module named spam is imported, the interpreter first searches for a built-in module with that name.当导入名为spam的模块时,解释器首先搜索具有该名称的内置模块。 If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path .如果未找到,它会在变量sys.path给出的目录列表中搜索名为spam.py的文件。 sys.path is initialized from these locations: sys.path从这些位置初始化:

  • The directory containing the input script (or the current directory when no file is specified).包含输入脚本的目录(或未指定文件时的当前目录)。

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH). PYTHONPATH(目录名称列表,语法与 shell 变量 PATH 相同)。

  • The installation-dependent default (by convention including a site-packages directory, handled by the site module).依赖于安装的默认值(按照惯例,包括一个站点包目录,由站点模块处理)。

A quick fix would be to use a relative import in C.py :一个快速的解决方法是在C.py中使用相对导入:

from .D import E

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

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