简体   繁体   English

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

[英]How to add own python modules to runtime environment

My python projects consists of a number of modules with import statements to each other.我的 python 项目由许多模块组成,相互之间有导入语句。 In my Eclipse PyDev environment these import statements are working well but when porting it to my Raspberry the runtime environment fails to load the dependent modules.在我的 Eclipse PyDev 环境中,这些导入语句运行良好,但是当将其移植到我的 Raspberry 时,运行时环境无法加载相关模块。

I have configured PYTHONPATH so that root directory of my project (/home/pi/Desktop/Projects/Catatumbo) is listed in sys.path :我已经配置了 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']

Project structure looks like:项目结构如下:

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

Though starting the script from project root directory via:虽然通过以下方式从项目根目录启动脚本:

sudo python3 forecast/adafruit/adafruit_forecast.py

still results in the following error:仍然导致以下错误:

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

Thanks for help!感谢帮助!

Kaya's remark brought me to the resolution by reading this helpful article :通过阅读这篇有用的文章, Kaya 的评论使我做出了决定:

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 .显式相对导入遵循 from 格式。 import X, where is prefixed by dots .导入 X,其中以 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.等等。一个隐式的相对导入就好像当前目录是 sys.path 的一部分一样。 Implicit relative imports are only supported in Python 2. They are NOT SUPPORTED IN PYTHON 3.隐式相对导入仅在 Python 2 中受支持。它们在 PYTHON 3 中不受支持。

Doing this, you will run into the issue of 'Parent module '' not loaded, cannot perform relative import' .这样做,您将遇到'Parent module'' not loaded, cannot perform relative import' 的问题 Running the script as a module will finally resolve the issue:将脚本作为模块运行将最终解决问题:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM