如何将自己的python模块添加到运行时环境

2024-09-26 22:11:16 发布

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

我的python项目由许多模块组成,每个模块之间都有import语句。在我的Eclipse PyDev环境中,这些import语句工作得很好,但是当将其移植到我的Raspberry时,运行时环境无法加载依赖模块

我已经配置了PYTHONPATH,以便我的项目的根目录(/home/pi/Desktop/Projects/Catatumbo)列在sys.path

['/var/www/upload/Projects/Catatumbo',
 '/home/pi/Desktop/Projects/Catatumbo',
 '/usr/lib/python35.zip',
 '/usr/lib/python3.5',
 '/usr/lib/python3.5/plat-arm-linux-gnueabihf',
 '/usr/lib/python3.5/lib-dynload',
 '/home/pi/.local/lib/python3.5/site-packages',
 '/usr/local/lib/python3.5/dist-packages',
 '/usr/lib/python3/dist-packages']

项目结构如下:

-core
--adafruit
---forecast (That's where the utility class resides)
-forecast
--adafruit  (That's where the script resides)

通过以下方式从项目根目录启动脚本:

sudo python3 forecast/adafruit/adafruit_forecast.py

仍然会导致以下错误:

File "forecast/adafruit/adafruit_forecast.py", line 35, in <module>
    from core.adafruit.forecast.forecast_colors import ForecastNeoPixelColors
ImportError: No module named 'core'

谢谢你的帮助


Tags: 模块项目coreimportadafruithome环境lib
1条回答
网友
1楼 · 发布于 2024-09-26 22:11:16

卡娅的话让我读到了这篇有用的article

A relative import uses the relative path (starting from the path of the current module) to the desired module to import. There are two types of relative imports:

an explicit relative import follows the format from . import X, where is prefixed by dots . that indicate how many directories upwards to traverse. A single dot . corresponds to the current directory; two dots .. indicate one folder up; etc. an implicit relative import is written as if the current directory is part of sys.path. Implicit relative imports are only supported in Python 2. They are NOT SUPPORTED IN PYTHON 3.

这样做,您将遇到'Parent module '' not loaded, cannot perform relative import'问题。将脚本作为模块运行将最终解决问题:

Use python -m package.module instead of python package/module.py

相关问题 更多 >

    热门问题