gpt4 book ai didi

Python 无法识别由 PYTHONPATH 设置的模块

转载 作者:太空宇宙 更新时间:2023-11-03 11:22:15 56 4
gpt4 key购买 nike

我已经搜索了一段时间以找到解决此问题的方法,但没有找到答案。我希望我能在这里找到一些帮助。如标题所示,python 无法识别已在我的 PYTHONPATH 中设置的模块。

我目前正在从事一个具有以下总体结构的项目:

base
├── util
│   └── logging_utility.py
└── project
└── app
├── config.py
└── runner.py

这是在 python 3.5 中通过名为 venv_1 的虚拟环境执行的。我使用运行 El Capitan 的 Mac。

我的 runner.py 脚本使用以下导入语句调用 logging_utility:

从 util.logging_utility 导入方法

执行时,我收到此错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'util.logging_utility'

我在终端中从目录的 base 级别运行它。我正在使用以下命令调用脚本:

PYTHONPATH=$HOME/base VIRTUAL_ENV=$HOME/.virtualenvs/venv_1 PATH=$VIRTUAL_ENV/bin:$PATH $HOME/.virtualenvs/venv_1/bin/python -- project/app/runner.py

现在,我尝试通过打印出我的 envsys.path 来调试它。在这两种情况下,base 目录都出现在路径中。那么,为什么我会收到此错误?

我还尝试将导入语句更新为 from base.util.logging_utility import method,这给了我以下错误:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'base'

知道为什么会这样吗?我该如何纠正?

谢谢!

更新

感谢BillyMoinuddin Quadri谁的建议解决了这个问题。出于某种原因,我仍然需要添加 __init__.py 文件。尽管 python 3.3+ 支持隐式导入,但看起来仍然需要它。这解决了问题。

最佳答案

您的 PYTHONPATH 中可能没有打包路径。为了添加它,请执行以下操作:

 import sys
sys.path.append('/absolute/path/to/base')

从 Python 3.3 开始,您不再需要 __init__.py

对于旧版本,另一个可能的原因是缺少__init__.py。如果目录中没有 __init__.py 文件,则无法导入该目录的文件。

Packages Document 中所述:

The __init__.py files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

关于Python 无法识别由 PYTHONPATH 设置的模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40683720/

56 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com