Python无法引用父模块中的模块。

11 浏览
0 Comments

Python无法引用父模块中的模块。

我正在尝试在Python中设置一个库。我创建了一个setup.py文件,在其中有一个库文件夹,然后我尝试创建一个示例和测试文件夹(用于包含示例代码和测试)。

文件夹:

- setup.py
- cvImageUtils # this is the library
     - __init__.py # this includs ColorUtils
     - ColorUtils.py # this includes a class called ColorUtils
- examples
     - color.py # this is shown below

ColorUtils文件夹内的init.py文件

from . import ColorUtils

ColorUtils.py

class ColorUtils:
    def __...

Color.py

from cvImageUtils import ColorUtils
m1 = cv2.imread(os.path.join(image_folder, "bb.jpeg"), 1)  # 1 = load color
cv2.imshow('grayscale', ColorUtils.convert_rbg_to_grayscale(m1))

起初,它说找不到模块,所以我根据另一个SO解决方案在文件顶部添加了以下内容:

import sys
sys.path.append('../')

现在对我来说已经有点折磨了,但它确实让我通过了找不到模块,但现在它说ColorUtils没有convert_rbg_to_grayscale的方法。所以我不得不将其更改为ColorUtils.ColorUtils.convert_rbg_to_grayscale

cv2.imshow('grayscale', ColorUtils.ColorUtils.convert_rbg_to_grayscale(m1))

我该如何设置文件夹,以便允许我在不声明ColorUtils两次的情况下包含库并调用它。

admin 更改状态以发布 2023年5月21日
0
0 Comments

在Python中,每个你想公开的目录(通常我们隐藏test.py)都需要一个init.py文件来进行模块搜索。这应该是一个经验法则,使用sys模块,你可以将模块添加到你的“模块搜索路径”中。

在目录中拥有init.py文件之后,你需要导入你想使用的包/模块/函数:-

import cvImageUtils.ColorUtils.convert_rbg_to_grayscale

你可以在Python中执行以下代码来查看你的sys路径中包含了哪些内容(由Python用于搜索模块/包):

import sys
sys.path

查看以下链接,获取更详细的解释:
https://www.programiz.com/python-programming/package
https://www.programiz.com/python-programming/modules#search

0
0 Comments

修改你的__init__.py文件:

from cvImageUtils.ColorUtils import ColorUtils

我认为你不再需要import sys,而且你不必重复导入ColorUtils了。但是,就像你必须实例化一个对象一样,你应该创建一个ColorUtils对象。

我个人的偏好是不为Utils创建一个类。

你可能已经这样做了,但是如果你想像在Python中那样直接使用类中的方法,你可能需要将它声明为static

class ColorUtils:
      @staticmethod
      def util_method():
          pass

然后你可以这样做:

ColorUtils.util_method()

更新:

你也可以在这里阅读更多关于相对/绝对导入的信息。

但是为了修复你的实际问题,你可以这样做:

color.py

  1. color.py中删除import syssys

  2. 将:import cvImageUtils.ColorUtils as ct
    更改为:from cvImageUtils.ColorUtils import *

  3. 删除所有的ct引用,而是直接使用实际函数。

cvImageUtils/__init__.py

将:from . import ColorUtils
更改为:__all__=['ColorUtils']

我能够在屏幕上打印出所有图像,并且还在本地生成了一个image.png文件。

0