将模块从父文件夹子文件夹导入脚本子文件夹 [siblings] 中的 运行
Importing module from parent folder subfolder to run in scripts subfolder [siblings]
我的项目结构如下所示:
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.
在脚本文件夹中的每个脚本中,我都是从以下代码开始的:
# 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
我的项目结构如下所示:
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.
在脚本文件夹中的每个脚本中,我都是从以下代码开始的:
# 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