启动时 Python 脚本,模块导入错误

启动时 Python 脚本,模块导入错误

我对 Python 没什么经验,但我编写了一个脚本,用于读取温度和压力并将其发送到 mysql 数据库。当我登录 ssh 并手动运行脚本时,一切正常。但是当我将脚本设置为在启动时启动时,它显示:

pi@raspberrypi:~ $ Traceback (most recent call last):
  File "/home/pi/code1.py", line 1, in <module>
    import mysql.connector
ImportError: No module named mysql.connector

与另一台树莓派上的另一个启动选项相同:

systemctl status sample.service
● sample.service - My Sample Service
   Loaded: loaded (/etc/systemd/system/sample.service; enabled; vendor preset: enabled)
   Active: failed (Result: exit-code) since Thu 2019-07-11 13:49:32 CEST; 4min 35s ago
  Process: 555 ExecStart=/usr/bin/python /home/pi/code1.py (code=exited, status=1/FAILURE)
 Main PID: 555 (code=exited, status=1/FAILURE)

Jul 11 13:49:31 localhost systemd[1]: Started My Sample Service.
Jul 11 13:49:32 localhost python[555]: Traceback (most recent call last):
Jul 11 13:49:32 localhost python[555]:   File "/home/pi/code1.py", line 1, in <module>
Jul 11 13:49:32 localhost python[555]:     import mysql.connector
Jul 11 13:49:32 localhost python[555]: ImportError: No module named mysql.connector
Jul 11 13:49:32 localhost systemd[1]: sample.service: Main process exited, code=exited, status=1/FAILURE
Jul 11 13:49:32 localhost systemd[1]: sample.service: Failed with result 'exit-code'.

我究竟做错了什么?

答案1

经过使用不同命令的一些测试后,我终于让它工作了。我必须像 rtaft 建议的那样全局安装它。我使用以下命令完成此操作:sudo -H pip install mysql-connector

谢谢 :)

答案2

它要么安装在你的主目录中,要么你正在使用虚拟环境。全局安装它。

sudo pip install mysql-connector-python

如果你正在使用virtualenv,那么你需要将其包装在shell脚本中并在该脚本中激活它,即myscript.sh:

source ~/pathtoproject/venv/bin/activate
python ~/pathtoproject/myscript.py

相关内容