Search code examples
python-3.xlinuxcrondebianraspberry-pi4

Run python script on raspberry pi 4 on startup/reboot


Dear People of Stackoverflow!

I am struggling to find a way to execute my python script on my Raspberry Pi4 on startup and reboot.

This would be a really basic Flask based API written in Python for manipulating a JSON Database with Post/Get HTTP requests.

I've already tried using crontab...

  • The path to my API.py script is: /home/apiadmin/Deploy/API.py
  • To the crontab file I've added the single line: @reboot python3 /home/apiadmin/API.py &

apiadmin supposed to be the root user

I can successfully safe the crontab file, upon rebooting and checking with crontab -l, the line is there. However upon rebooting the Raspberry Pi the API is not reachable/script is not running

When I run it from PuTTY with the command: python3 /home/apiadmin/Deploy/API.py the script runs fine, and the API is on line, and every request works fine

Also I've tried using a launcher.sh, turning it to an executable but that fails saying it can't cd into the directory (same path) because it doesn't exist.

Also tried with a 30 second sleep to begin with... Didn't solve the problem.

Thank you in advance!


Solution

  • Lets use the systemd system and service manager, first we create a new service in /etc/systemd/system, something like sudo nano /etc/systemd/system/api.service

    Then paste this inside, it contain the information about your API:

    [Unit]
    Description=My API Service
    After=network.target
    
    [Service]
    ExecStart=/usr/bin/python3 /home/apiadmin/Deploy/API.py
    WorkingDirectory=/home/apiadmin/Deploy
    StandardOutput=inherit
    StandardError=inherit
    Restart=always
    User=apiadmin
    
    [Install]
    WantedBy=multi-user.target
    

    THen we save and give it the proper permissions sudo chmod 644 /etc/systemd/system/api.service.

    Now if you want to start it just do sudo systemctl start api.service and if you want to start it it on boot sudo systemctl enable api.service