1

I am having troubles running a python server script at startup on my RPi 3 B+.

I created a python file and placed it in /home/pi/Desktop/scripts/bulb.py, it contains the python interpreter should be used in the start (#!/usr/bin/python3) and has proper permissions (chmod 777 bulb.py).

When running /home/pi/Desktop/scripts/bulb.py at the terminal, the server runs fine. I created a systemd service as following:

[Unit]
Description=The bulb server
After=network-online.target

[Service]
ExecStart=/home/pi/Desktop/scripts/bulb.py

[Install]
WantedBy=multi-user.target

and then ran sudo systemctl enable bulbserver in order to enable it. However, when rebooting, it is not running and when running systemctl status bulbserver I can see the script is exited because of an error "ImportError: No module named 'yeelight'", I am using this module, but why when running the file from the terminal it works but when systemd tries to run it, it failes with apparently a different interpreter?

3

As previously mentioned, systemd services are ran by the root user instead of the pi user. However, you can configure your .service file to run the script as a different user.

Under the [Service] area in your .service file, add the following line:

User=pi

Your .service file should look like this:

[Unit]
Description=The bulb server
After=network-online.target

[Service]
ExecStart=/home/pi/Desktop/scripts/bulb.py
User=pi

[Install]
WantedBy=multi-user.target

This line will run your script as the pi user, with the same permissions that the pi user has.

Remember to either reboot or run the following commands:

systemctl daemon-reload
systemctl restart bulbserver.service
  • thanks for the solution. i solved it by installing the package to the root user by sudo pip -H install yeelight – user3731180 Jun 11 '18 at 22:22
0

Startup scripts are run with user root, not user pi. This means that the directory and environment at startup are different than when you run the script when logged in as pi. When writing startup scripts on the Raspberry Pi, you can change the effective user to pi by:

cd /home/pi
sudo -u pi my_startup_script

If you want to save the output of your startup script for later reference:

cd /home/pi
sudo -u pi bash -c "my_startup_script >& my_startup_log"

You basically need another script that will run as root to launch your actual startup script.

  • No need to cd if you use absolute path. – Fabian Jun 12 '18 at 10:35
  • Actually, startup scripts tend to have environments tied to the invocation directory instead of the script directory. I have been burned many times by not using the "cd". – OyaMist Jun 12 '18 at 13:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.