首页 > 解决方案 > 如何在同一根目录但在不同的子目录中导入 Python 模块?

问题描述

我在一个名为“API”的父文件夹中有许多 Python 文件,我正在尝试将它们链接在一起:

API/auth/module1.py
API/子文件夹/prgm.py

从父文件夹到子文件夹,我有一个包含要调用的路径或程序名称的init .py 文件,但是当我去执行调用 import 'module1.py' 的 '/subfolder/prgm.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'

这是import我在“prgm.py”中的声明:

from API.auth import module1

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

标签: pythonpython-3.6python-module

解决方案


如果你真的需要运行 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

推荐阅读