3

I run into a question that I want to auto run a server in python when boot the Raspberry Pi every time. I tried several methods but they all don't work for me. Assume my python file is

/home/pi/Desktop/server.py

I tried to use crontab and wrote

@reboot python /home/pi/Desktop/server.py &

But it doesn't work. I check the the server doesn't start. I also tried to wrote in /etc/rc.local

python /home/pi/Desktop/server.py &

Still doesn't work.

Only wrritten in

/home/pi/.bashrc

works now. But it needs me to use ssh to remote login in and then start run the server. What I want is just the server would auto run after I reboot the Pi, not needing to login in. Anyway has ideas?

3
  • 2
    How do you run your script without autorunning it - or more importantly: does it include the shebang in the beginning #!/usr/bin/python3?
    – Ghanima
    Aug 27, 2017 at 8:33
  • Just login in to my Pi, and run python /home/pi/Desktop/server.py in terminal
    – Tian Xie
    Aug 27, 2017 at 20:57
  • Forget about the shebang I asked for. Try adding the full path of the python interpreter in your crontab statement (most likely / usr/bin/python. Cron is known to be peculiar about that. Note also that there is no need for an ampersand in crontabs (though that should not make it fail either).
    – Ghanima
    Aug 27, 2017 at 21:08

2 Answers 2

3

Since you call your script a server, I assume it needs network connection to run properly. Therefore you should consider running it via systemd with network-online.target as a dependency:

Create a file /etc/systemd/system/my_server.service:

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

[Service]
ExecStart=/home/pi/Desktop/server.py

[Install]
WantedBy=multi-user.target

and run:

sudo systemctl enable my_server

Don't forget to add a shebang line to your script as @Ghanima has explained in the comments.

-1

Try the next things:
1. Edit /etc/rc.local
2. At the end, add the next command: sudo python /home/pi/Desktop/server.py &
Let me know if it helps.

UPDATE:

Lets try a different method:
1) in /etc/init.d/ folder create file (ex. mypythonscript)
2) give it execution permissions: sudo chmod 755 mypythonscript
3) in the file, add the next code:

#!/bin/sh
#/etc/init.d/mypythonscript

case "$1" in
  start)
    echo "Starting My Python Script"
    python /home/pi/Desktop/server.py &
    ;;
  stop)
    echo "Stopping My Python Script"
    killall python
    ;;
  *)
    echo "Usage: /etc/init.d/mypythonscript{start|stop}"
    exit 1
    ;;
esac

exit 0

4) After that run the next command:

sudo update-rc.d /etc/init.d/mypythonscript defaults

Let me know if it helps.

1
  • Thanks, but it doesn't work. Everything in re.local runs as root user.
    – Tian Xie
    Aug 27, 2017 at 21:16

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.