Main Menu

search

You are here

Run Python program from script file at Linux startup

[last updated: 2017-09-09]
-----

This is for Python on rPi

  • Summary of how it works:
    • when you boot up, rc.local gets executed
    • in rc.local, you have put a script file (...sh) that gets executed
    • in your .sh file, you have one line, (eg. sudo python ...filename)
      that executes the python program you want to have run at bootup

    ---------------------------

  • Using a script file (.sh) in rc.local:
    • If you put a script file in rc.local, it will be executed every time you boot up.
      First you must create a script program containing a line to execute your python program
      • Create a file. It can have any un-used name, but must have a .sh extension.
        eg. create a file (using your preferred text editor) named runAtStartup.sh
        save the file wherever you want, but I put mine in /home/pi/Desktop/MyDocs/programs/scriptFiles/
      • It will have one line in it:
        sudo python [path/filename.py] &
        (if your program has an infinite loop, eg. a callback keypress routine, then you must add the "&" so it will continue to run in the background and let the rest of your rPi opsys boot up)
        or, in my case:
        sudo python /home/pi/Desktop/MyDocs/programs/python/sysFiles/autoRunAtStartup.py &
    • Make the script file executable:
      • from LXTerminal, execute:
        $ sudo chmod +x [path/filename.sh]
    • Then you add the script to the rc.local file that gets executed at startup
      • In LXT, navigate to the location of the rc.local file:
        $ cd /etc
      • open nano to edit the file:
        $ sudo nano rc.local
      • add this line at the end of the file, just above/before the 'exit 0' line:
        [path/filename.sh]
      • type ctrl-o to save, <cr> to confirm, and ctrl-x to exit nano
    • reboot to execute.

    .

    .

    .

    eof