从父文件夹子文件夹导入模块以在脚本子文件夹中运行[兄弟姐妹]

问题描述 投票:0回答:3

我的项目结构如下所示:

project/
|--- helper_modules/
    |--- util.py
|--- scripts/
    |--- A.py

如果我将脚本A.py放在项目/文件夹中,它将使用from helper_modules.util import fn成功运行并导入。但是我有很多脚本,为了保持组织有序,我希望将它们全部放在自己的子文件夹中。我怎么能这样做,仍然从helper_modules导入?

当我调用脚本时,我在目录/ project /中。

python python-3.x python-module
3个回答
1
投票

您只需要在脚本A.py中添加它:

from ..helper_modules.util import fn

并从项目文件夹中运行A.py退出一个级别,因此如果您在项目文件夹中,请执行以下操作:

cd ..

然后使用A.py运行

python -m project.scripts.A

0
投票

我发现这给了我一个解决方法。显然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('.'))

0
投票

如果您当前的目录是/project/,则应使用以下命令启动脚本:

python -m scripts.A

scripts/A.py,你可以做到

from helper_modules.util import fn
© www.soinside.com 2019 - 2024. All rights reserved.