首页 > 解决方案 > Python:在另一个包中导入一个包而不使用完整路径

问题描述

我有一些代码无法正确导入 [在 Linux 上]:

文件(每个 python 文件只包含一个具有相同名称和大小写的类):

commandreader/
|-- CommandReader.py
|-- y/
    |-- Switch.py
    |-- Option.py
    |-- __init__.py
    |-- x/
        |-- InputArg.py
        |-- __init__.py

CommandReader.py 的导入:

from y import Switch
from y import Option

y/Switch.py​​ 和 y/Option.py 的导入:

from x import InputArg

y/__init__.py:

from .import x
from .Switch import Switch
from .Option import Option

y/x/__init__.py:

from .InputArg import InputArg

错误:

$ python3 ./CommandReader.py
Traceback (most recent call last):
  File "CommandReader.py", line 12, in <module>
    from y import Switch
  File "/home/swatts/code/commandreader/y/__init__.py", line 2, in <module>
    from .Switch import Switch
  File "/home/swatts/code/commandreader/y/Switch.py", line 8, in <module>
    from x import InputArg
ModuleNotFoundError: No module named 'x'

编辑:除了我的错误,我是否误解了 Python 希望包如何工作?因为这就是我的印象。

标签: pythonimportmodulepackagepythonpath

解决方案


一种解决方案是,您可以在环境变量中添加模块的路径:

添加在Path其中的路径Environmental Variable

如果您正在使用Windows

  1. 右键单击My Computer并转到Properties
  2. 选择Advanced system settings
  3. 转到选项卡Advanced
  4. 点击Environment Variables
  5. System Variables部分搜索Path变量
  6. 双击它并在其value字段列表中添加路径。

您也可以使用代码:

import sys
sys.path.append(path)
print(sys.path)

推荐阅读