python - 如何在同一根目录但在不同的子目录中导入 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 脚本和调用位于子文件夹中的模块。
解决方案
如果你真的需要运行 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
推荐阅读
- javascript - Angular4应用程序中的HTML转义拦截器
- android - 经典蓝牙发现没有提供除 MAC 地址以外的详细信息
- javascript - 如何使用 reduce() 从 javascript 中的嵌套数据中提取信息?(ES6)
- sql-server - 在java和数据库中自动生成具有特定格式的主键
- marklogic - MLCP 使用文档选择器导出所选文档
- postgresql - psql select * from user 返回系统用户而不是表内容
- mysql - System.AggregateException:Xamarin 发生一个或多个错误
- kubernetes - 从外部访问特定的 pod
- css - 如何将所有菜单项与徽标内联?
- javascript - 防止在 PHP 中下载 PDF