python模块未找到错误没有名为的模块

2024-04-26 00:44:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我有几个单独的pythone文件,我正在使用它们导入另一个py文件。试图导入它们的模块位于单独的文件夹中,下面是代码示例

from tez.library.image_crop import ImageCrop
from tez.library.image_process import ImageProcess
from tez.library.image_features import ImageFeatures
from tez.const.application_const import ApplicationConst
from tez.library.file_operation import FileOperation

这段代码就是我希望使用commond行作为“pythonsample1.py”启动py文件的地方,并抛出一个错误,如下所示

Traceback (most recent call last): File "samples1.py", line 1, in from tez.library.image_crop import ImageCrop ModuleNotFoundError: No module named 'tez'

文件夹结构:

.tez
-- library
---- image_crop.py
---- image_process.py
---- image_features.py
--src
---- samples1.py

Python版本:3.8
Pip:20.0.2
Windows 10 Pro 1909


Tags: 文件代码frompycropimageimport文件夹
2条回答

如果您正在构建一个名为tez的包(既然您试图导入它,我想您是这样的)。然后,所有关于tez的事情都需要在本地进行。tez包中的所有文件都需要使用“.”和“.”导入相互引用

在samples1.py中:

from ..library.image_crop import <something>

编辑:

听起来你好像误解了python是如何导入东西的。在python脚本中运行“import X”时,python会在sys.path下查找名为X的包。如果要查找自定义包,可以将其附加到脚本顶部的sys.path

import sys
sys.path.append(<directory of tez>)

import tez

但是,强烈建议您不要从程序包名称目录结构下的文件导入。如果“examples”是使用包“tez”的示例目录,那么“examples”应该位于包“tez”之外。如果“示例”在包“tez”中,那么“示例”应该是在包中进行本地导入

掌握软件包的使用可能很棘手

sample.py无法看到上面的src文件夹,但您可以告诉Python这样做:

import sys
import os
tez = os.path.dirname(os.path.dirname(__file__))
# __file__ is path of our file (samples.py)
# dirname of __file__ is "src" in our state
# dirname of "src" is "tez" in our state

sys.path.append(tez) # append tez to sys.path, python will look at here when you try import something

import library.image_crop # dont write "tez"

但我认为这不是一个很好的设计

相关问题 更多 >