【发布时间】:2020-01-24 14:38:10
【问题描述】:
我有一些代码无法正确导入 [在 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 希望包如何工作?因为这就是我的印象。
【问题讨论】:
-
如果你改为运行
python3 -m CommandReader会发生什么?我建议先使用绝对导入,然后在一切正常后最终切换到相对导入。最终在一个相对相似的问题上看到这个答案:stackoverflow.com/a/59768291/11138259
标签: python import module package pythonpath