1

I want my pi to run a python script on it everytime I plug it into any power source. My pi collects data from MSP430x and upload it on a cloud server. I want to keep it running all the time and I can't afford to keep it connected to my laptop for whole day. Can anyone tell me how to do that?

Ghanima
  • 15,855
  • 15
  • 61
  • 119

2 Answers2

3

rc.local (Simple)

You can run commands by adding them to /etc/rc.local. Each command/script must not have any ouput and /etc/rc.local must exit 0 when it completes.

Here is an example:

python /full/path/to/py.py arg1, arg2 > /dev/null
bash /home/user/startup-script.sh > /dev/null
exit 0

crontab (lenik)

An easy and robust way would be using crontab instead of messing with rc.local or (worse) creating broken daemon scripts. keyword @reboot does all the magic:

$ crontab -e
no crontab for pi - using an empty one

Select an editor. To change later, run 'select-editor'.

  1. /bin/ed
  2. /bin/nano <---- easiest
  3. /usr/bin/vim.tiny

Choose 1-3 [2]: 2 crontab: installing new crontab $ crontab -l

m h dom mon dow command

@reboot /home/pi/script_to_run_on_reboot

Make sure your /home partition is not encrypted and is already mounted during the boot process, otherwise you might need to change the place for your script.

init.d (Daemon)

You could create an upstart script and place it into your /etc/init.d/ directory. You would then need to make sure it's executable and add it to startup via update-rc.d.

  • vim /etc/init.d/startup-daemon
  • chmod +x /etc/init.d/startup-daemon
  • update-rc.d startup-daemon defaults
  • update-rc.d startup-daemon enable

You will need to spend some time learning about daemons, if you chose this method.


Note

In the future, be sure to give some specs, such as your operating system.

earthmeLon
  • 1,404
  • 1
  • 11
  • 23
3

easiest and more robust way would be using crontab instead of messing with rc.local or (worse) creating broken daemon scripts. keyword @reboot does all the magic:

$ crontab -e
no crontab for pi - using an empty one

Select an editor.  To change later, run 'select-editor'.
  1. /bin/ed
  2. /bin/nano        <---- easiest
  3. /usr/bin/vim.tiny

Choose 1-3 [2]: 2
crontab: installing new crontab
$ crontab -l
# m h  dom mon dow   command
@reboot /home/pi/script_to_run_on_reboot

just make sure your /home partition is not encrypted and is already mounted during the boot process, otherwise you might need to change the place for your script.

lenik
  • 11,541
  • 1
  • 30
  • 37