اجرای اتوماتیک یک برنامه پایتون بعد از بووت کامل
When using the Raspberry Pi, many times you may have a program you want to automatically start it at boot so that you can use your project without logging in to the RaspberryPi via SSH or VNC. Unlike the Arduino, the Pi needs to be set up to run a program automatically.
This tutorial will demonstrate how to auto-run Python programs on the Raspberry Pi, especially at startup.
Running programs automatically can help in robotics project where you want the robot to automatically start doing something or responding to commands as soon as the Raspberry Pi turns on.
One of the easiest ways of doing this is to use crontab.
Crontab is a table used by cron which is a daemon which is used to run specific commands at a particular time. Crontab is very flexible: you can use Crontab to run a program at boot or to repeat a task or program at 12 PM every Wednesday.
To use crontab with your Raspberry Pi to automate your programs, follow these step:
- Write your program and note down its location. We’ll be using a program called py_test.py and save it at /home/pi/Desktop/pyprog
- Now open crontab. You may need to open crontab in root (add sudo before the command!).
- Add a new entry at the very bottom with @reboot to specify that you want to run the command at boot, followed by the command. Here we want to run the python program and save the output in log.txt, so our entry is
12@reboot sudo python /home/pi/Desktop/pyprog/pytest.py/home/pi/Desktop/pyprog/log.txt
- Now save the file and exit.
۱ ۲ ۳ ۴ ۵ /path/to/command arg1 arg2
۱ = Minutes (0 – ۵۹)
۲ = Hours (0 – ۲۳)
۳ = Days (0 – ۳۱)
۴ = Month (0 – ۱۲)
۵ = Day of the week (0 – ۷) (Sunday is the 0 day)
On the other hand instead of the first five fields you can use one of the seven special strings that define for you with an easiest way what you want to do. Those strings are the following:
@reboot = Run once, at startup.
@yearly = Run once a year
@monthly = Run once a month
@weekly = Run once a week
@daily = Run once a day
@midnight = Pretty much the same as @daily
@hourly = Run once an hour
- When you restart the pi, the command will be run and we will get the output log file.Be a bit careful with the permissions and making sure that your program runs properly before you put it on boot: you can waste a lot of time trying to figure out what went wrong!
- Having trouble? Check your bootlog:
grep cron /var/log/syslog