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

2024-04-20 12:15:06 发布

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

我安装了一个python包,它有下面的dir结构。在

pkg_name/
  __init__.py
  work.py
  helper.py

在工作.py,导入操作如下-

^{pr2}$

它在python2.7虚拟环境中运行良好,但在python3venv中给出了以下错误

ModuleNotFoundError: No module named 'helper'

我修改了工作.py通过在下面添加“.”导入语句,然后它在python3中可以正常工作。在

from .helper import MyClass

问题-有没有办法让它在python3中运行而不修改包文件?(或者发布包时只记住python2)

编辑:在下面添加\uu init_uy.py内容

from .work import Sample
from .helper import MyClass

Tags: namefrompyimporthelperinit错误dir
2条回答

我想你运气不好了。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.

有关这个变化的更多信息,请参阅这张大约16年前的PEP。在

我建议停止使用python2,习惯python3的工作方式。在

python路径中是否有helper.py将决定是否可以直接导入它。在

如果您没有显式地设置PYTHONPATH,那么您尝试运行脚本的目录将被添加到PYTHONPATH中。在

附录:

如果我们尝试导入具有相对导入的内容:

from .module import data

建议。在

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

^{pr2}$

避免任何歧义。在

相关问题 更多 >