python - 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 希望包如何工作?因为这就是我的印象。
解决方案
一种解决方案是,您可以在环境变量中添加模块的路径:
添加在Path
其中的路径Environmental Variable
如果您正在使用Windows
- 右键单击
My Computer
并转到Properties
- 选择
Advanced system settings
- 转到选项卡
Advanced
- 点击
Environment Variables
- 在
System Variables
部分搜索Path
变量 - 双击它并在其
value
字段列表中添加路径。
您也可以使用代码:
import sys
sys.path.append(path)
print(sys.path)
推荐阅读
- git - Kubernetes cronjob - git pull else git clone
- bash - 计算具有唯一名称的嵌套目录的数量
- amazon-web-services - 在 lambda 上使用 dynamoDB 时出现 AWS Lambda 权限错误
- python - Leetcode 3Sum:为什么结果重复?
- python - 如何在 Django 中使用 Css + JavaScript 文件渲染 HTML
- react-native - React-native 应用程序标题与电话标题重叠
- json - JSONDecodeError:期望值:第 1 行第 1 列。Python 请求
- python - 如何在python中修改Matlab脚本来调用数据
- flutter - 检查字符串飞镖中的数学方程
- python - 如何解决boto3客户端错误?service_nake