有在父文件夹从另一个文件导入类
问题描述:
的文件的问题,我需要在目录中的样子有在父文件夹从另一个文件导入类
face/util/load_data.py
face/preprocessing.py
preprocessing.py定义的类FaceDetector
,FaceAligner
和方法clip_to_range
我想导入这些类到load_data.py 我想执行这个状态换货内load_data.py
from preprocessing import FaceDetector, FaceAligner, clip_to_range
我收到错误
Traceback (most recent call last):
File "utils/load_data.py", line 7, in <module>
from preprocessing import FaceDetector, FaceAligner, clip_to_range
ImportError: cannot import name 'FaceDetector'
能否请你告诉我如何正确地导入这些类?
答
你可以尝试添加__init__.py
,这将使你导入的脸模块,那么你可以导入喜欢,
from face.preprocessing import FaceDetector, FaceAligner, clip_to_range
更新: 另一种方式是在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)
import preprocessing
答
将preprocessing.py
移动到util目录。
查找执行文件路径中的文件。
如果你不想改变目录结构。添加下面的代码。
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)
无论目录结构如何,导入都是可能的。
你会解决的。
哪个文件先执行? – Montreal
我只执行load_data.py – benedemon
python3 utils/load_data.py – benedemon