pythonsystemctl

Python script not working through systemctl .service file


I'm trying to set up a simple script to run with systemctl timer.

To test if the .service file works i launch it: sudo systemctl start mioScript.service but nothing happen. If i check the status:

mioScript.service - Myscript
     Loaded: loaded (/etc/systemd/system/mioScript.service; disabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Sat 2024-04-13 14:38:57 CEST; 7s ago
TriggeredBy: ● mioScript.timer
    Process: 3804 ExecStart=/usr/bin/python3 /home/user/main.py (code=exited, status=1/FAILURE)
   Main PID: 3804 (code=exited, status=1/FAILURE)
        CPU: 58ms

Apr 13 14:38:57 server systemd[1]: Started Mio.
Apr 13 14:38:57 server python3[3804]: Traceback (most recent call last):
Apr 13 14:38:57 server python3[3804]:   File "/home/user/main.py", line 1, in <module>
Apr 13 14:38:57 server python3[3804]:     from requests import Request, Session
Apr 13 14:38:57 server python3[3804]: ModuleNotFoundError: No module named 'requests'
Apr 13 14:38:57 server systemd[1]: mioScript.service: Main process exited, code=exited, status=1/FAILURE
Apr 13 14:38:57 server systemd[1]: mioScript.service: Failed with result 'exit-code'.

but if i open a terminal and i type: /usr/bin/python3 /home/user/main.py the script works fine.

I do not understand why launching the script throught the systemctl .service file do not find the requests module of Python (the module is already installed on the computer). Am i launching properly the script? or should i launch it in another way?


Solution

  • I'm not sure exactly what you have written in your script file. But it looks like environment conflict so you can try out 2 general ways to fix it.

    1. Set PYTHONPATH in environment variable.

      In your .service file, try adding Environment="PYTHONPATH=path/to/modules".

    2. Use virtual environment.

      Try adding ExecStart=/path/to/your/venv/bin/python3 /home/user/main.py and install all your dependency in the environment beforehand.