如何在同一根目录但在不同的子目录中导入 Python 模块?

How do I import a Python module in the same root directory but in a different sub-directory?

我在名为 'API' 的父文件夹中有许多 Python 个文件,我正在尝试 link 将它们放在一起:

API/auth/module1.py
API/subfolder/prgm.py

从父文件夹到子文件夹,我有一个 init.py 文件,其中包含要调用的路径或程序名称,但是当我执行 '/subfolder/prgm .py' 调用导入 'module1.py',我在执行时收到以下错误:

machine01% ./prgm.py
Traceback (most recent call last):
  File "./prgm.py", line 2, in <module>
    from API.auth.module1 import authFunction
ModuleNotFoundError: No module named 'API'

这是我在 'prgm.py' 中的 import 语句:

from API.auth import module1

这个问题与之前的问题有点不同,因为我试图获取一个已经在一个子文件夹中的 python 脚本来访问另一个子文件夹中但在同一父文件夹下的模块 'API' 文件夹。以前的问题涉及 python 脚本基于父文件夹和调用位于子文件夹中的模块。

尝试“”"from . auth import module1"””可能是?

如果你真的需要 运行 API/subfolder/prgm.py 依次导入 API/auth/module1.py

在 prgm.py 中,您可以将父目录(即 'API')添加到 sys.path,如下所示:

import os, sys, inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

现在您可以从 'API':

中导入任何内容
from auth import module1