CodexBloom - Programming Q&A Platform

Ubuntu 22.04 - Custom Python script scenarios with 'ImportError' when run as a systemd service

πŸ‘€ Views: 2 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-05
python systemd ubuntu Python

I'm trying to debug Hey everyone, I'm running into an issue that's driving me crazy... I'm working with an scenario with a custom Python script that runs perfectly from the terminal but fails with an 'ImportError' when executed as a systemd service on Ubuntu 22.04. The script, located at `/usr/local/bin/my_script.py`, imports a custom module from `/usr/local/lib/my_module.py`. When I try to start the service using `systemctl start my_script.service`, I see the following behavior in the logs: ``` my_script.py: ImportError: No module named 'my_module' ``` Here’s my systemd service file located at `/etc/systemd/system/my_script.service`: ```ini [Unit] Description=My Custom Python Script [Service] ExecStart=/usr/bin/python3 /usr/local/bin/my_script.py WorkingDirectory=/usr/local/bin User=myuser Environment=PYTHONPATH=/usr/local/lib [Install] WantedBy=multi-user.target ``` I've ensured that the permissions on the script and the module are correct and that `myuser` has access to them. I also tried adding `PYTHONPATH` directly in the service file, but the behavior continues. When I run the script from the terminal as `myuser`, everything works without scenario. Is there something I’m missing in the systemd configuration that prevents the script from finding the module? Any suggestions on how to resolve this would be greatly appreciated. I'm working on a CLI tool that needs to handle this. I'm using Python latest in this project. Any suggestions would be helpful.