【发布时间】:2021-10-29 20:53:30
【问题描述】:
我的项目结构如下:
python-test » tree
.
├── asdf
│ ├── __init__.py
│ ├── mycode2.py
│ ├── mycode.py
│ └── scripts
│ └── __init__.py
├── __init__.py
└── scripts
├── __init__.py
└── mymod.py
asdf/mycode.py 包含:
import scripts.mymod
而scripts/mymod.py 包含:
print('hello world')
所有__init__.pys 都是空的。
我想导入scripts.mymod。
我正在运行 asdf/mycode.py 失败,因为它正在查看 asdf/scripts 而不是 mymod 的根 scripts 文件夹。
> PYTHONPATH=: python asdf/mycode.py
Traceback (most recent call last):
File "asdf/mycode.py", line 1, in <module>
import scripts.mymod
ModuleNotFoundError: No module named 'scripts.mymod'
作为一种解决方法,我可以手动修改路径,我已经在asdf/mycode2.py 中完成了。
import sys
sys.path = [p for p in sys.path if 'asdf' not in p]
import scripts.mymod
这可以正常工作:
> PYTHONPATH=: python asdf/mycode2.py
hello world
有没有办法在asdf/mycode.py 中导入scripts.mymod 无需手动修改sys.path,并且无需更改必须设置为: 的PYTHONPATH? p>
【问题讨论】:
-
您可以在项目目录中使用主入口点。
python-test/main.py如果您从主目录运行代码。您可以使用from asdf.scripts import ...或from scripts import mymod导入。
标签: python path python-import