在 python3 中未检测到模块,但在 python2 中工作

Module not detected in python3 but works in python2

我安装了一个 python 包,它的目录结构如下。

pkg_name/
  __init__.py
  work.py
  helper.py

在 work.py 中,导入完成如下 -

from helper import MyClass

它在 python2.7 虚拟环境中运行良好,但在 python3 venv

中出现以下错误

ModuleNotFoundError: No module named 'helper'

我通过添加“.”修改了 work.py 导入语句。如下所示,然后它在 python3.

中工作正常
from .helper import MyClass

问题 - 有没有办法在不修改包文件的情况下在 python3 中实现 运行? (或者发布包时仅记住 python2)

编辑:在下面添加 __init__.py 内容

from .work import Sample
from .helper import MyClass

我认为你 运行 运气不好。 Python 3 的 documentation 状态:

Relative imports use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots indicate a relative import to the parent(s) of the current package, one level per dot after the first.

有关此更改的更多信息,请参阅此 PEP 近 16 年前的内容。

我建议停止使用 Python 2 并习惯 Python 3 的工作方式。

您的 python 路径中是否有 helper.py 将决定您是否能够直接导入它。

如果您没有明确设置 PYTHONPATH,您尝试 运行 您的脚本所在的目录将被添加到 PYTHONPATH。

附录:

如果我们尝试通过相对导入导入某些内容:

from .module import data

建议。

但是,最好像这样提供完整路径:

from pkg_name.helper import MyClass

避免歧义。