从子目录或相对路径导入包 [英] importing a package from a subdir or relative path
问题描述
这是我的目录设置:
mydir
├── script1.py
└── shared
├── otherstuff
├── script2.py
└── pkg
├── box.py
└── __init__.py
script2.py
以
import pkg
,效果很好.当我在script1.py
中包含同一行时,我得到:
and it works great. When I include the same line in script1.py
, I get:
Traceback (most recent call last):
File "script1.py", line 1, in <module>
import pkg
是否有什么好方法可以使在script1.py
中使用的语法简单?在过去的一个小时中,我一直在阅读有关PYTHONPATH
和sys.path
的信息,但是我正在尝试为我的仓库提供一些基本功能,而且我不相信它每次需要时都需要修改PYTHONPATH
运行脚本.
Is there any good way to get syntax that simple to work in script1.py
? I have been reading about PYTHONPATH
and sys.path
for the past hour, but I'm trying to make some basic functions available to my repo, and I can't believe that it will require modifying PYTHONPATH
everytime I want to run a script.
我在这里想念什么?将pkg
放入script1.py
的最佳方法是什么?
What am I missing here? What's the best way to get pkg
into script1.py
?
推荐答案
您必须这样做:
from shared import pkg
此外,您的shared
目录应具有__init__.py
文件
Also, your shared
directory should have an __init__.py
file
这篇关于从子目录或相对路径导入包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!