我的项目结构如下所示:
project/
|--- helper_modules/
|--- util.py
|--- scripts/
|--- A.py
如果我将脚本A.py放在项目/文件夹中,它将使用from helper_modules.util import fn
成功运行并导入。但是我有很多脚本,为了保持组织有序,我希望将它们全部放在自己的子文件夹中。我怎么能这样做,仍然从helper_modules导入?
当我调用脚本时,我在目录/ project /中。
您只需要在脚本A.py中添加它:
from ..helper_modules.util import fn
并从项目文件夹中运行A.py退出一个级别,因此如果您在项目文件夹中,请执行以下操作:
cd ..
然后使用A.py运行
python -m project.scripts.A
我发现这给了我一个解决方法。显然this can't be done by default in Python.
在scripts文件夹的每个脚本中,我都是从这段代码开始的:
# add to the Python path to import helper functions
import sys
import os
sys.path.append(os.path.abspath('.'))
如果您当前的目录是/project/
,则应使用以下命令启动脚本:
python -m scripts.A
从scripts/A.py
,你可以做到
from helper_modules.util import fn