0

I have a Python script which I'd like to run at startup. However when I run it as a systemd service, it seems to be unable to find one of the modules. Here's the status message:

● mqttproc.service - MQTT Post-processor
     Loaded: loaded (/etc/systemd/system/mqttproc.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Mon 2021-12-06 11:10:45 GMT; 2min 31s ago
    Process: 2375 ExecStart=/usr/bin/python3 /home/ken/python/mqttproc/mqttproc.py (code=exited, status=1/FAILURE)
   Main PID: 2375 (code=exited, status=1/FAILURE)

Dec 06 11:10:45 MintVM systemd[1]: Started MQTT Post-processor.
Dec 06 11:10:45 MintVM python3[2375]: Sensor positions [100.0, 80.0, 60.0, 40.0, 20.0, 0.0] (Litres)
Dec 06 11:10:45 MintVM python3[2375]: Traceback (most recent call last):
Dec 06 11:10:45 MintVM python3[2375]:   File "/home/ken/python/mqttproc/mqttproc.py", line 131, in <module>
Dec 06 11:10:45 MintVM python3[2375]:     import paho.mqtt.client as mqtt
Dec 06 11:10:45 MintVM python3[2375]: ModuleNotFoundError: No module named 'paho'
Dec 06 11:10:45 MintVM systemd[1]: mqttproc.service: Main process exited, code=exited, status=1/FAILURE
Dec 06 11:10:45 MintVM systemd[1]: mqttproc.service: Failed with result 'exit-code'.

The bizarre thing is this script runs without fail from the commandline. I even have it running as a systemd service on another machine. My .service file is as simple as they come:

[Unit]
Description=MQTT Post-processor

[Service]
ExecStart=/usr/bin/python3 /home/ken/python/mqttproc/mqttproc.py
WorkingDirectory=/home/ken/python/mqttproc

[Install]
WantedBy=multi-user.target

Can anyone point out the obvious thing I'm missing, please?

Thanks in advance.

KDM
  • 103
  • 3

1 Answers1

0

Jobs run through cron, or systemd startup scripts aren't run in the same runtime environment that you have on your desktop. systemd startup scripts are run as root. None of your PATH changes, or other environment variable settings from ~/.bashrc are automatically propagated to your cron job. For example, there's no $DISPLAY, so GUI programs need special treatment (read man xhost).

One can set environment variables for all one's cron jobs in the crontab file Read man 5 crontab.

Look at the results of echo "=== id ===";id;echo "=== set ===";set;echo "=== env ===";env | sort;echo "=== alias ===";alias in each of your environments.

waltinator
  • 4,439
  • 1
  • 16
  • 21