Scenario

I recently wanted my Python program to execute right after the system boots up. I discovered several options to achieve this, eliminating the need for manual intervention to run the program.

Option 1: Editing through Crontab

  1. Open a terminal with elevated privileges: sudo su -
  2. Edit the crontab configuration: crontab -e
  3. Add the following command to start the Python program (assuming you want to run it on a Raspberry Pi terminal): ```bash
  4. @reboot /usr/bin/python3 /path/to/your/script.py

Option 2: Editing through services using systemd

  • Create a script, name it as “myscript.sh”
  • Make the script executable: chmod +x myscript.sh
  • Navigate to the systemd directory: cd /etc/systemd/system/
  • Create a service file named “myscript.service” inside the systemd directory.
  • And below lines using nano myscript.sh
Description=My Script

[Service]
ExecStart=/path/to/myscript.sh
WorkingDirectory=/path/to/
StandardOutput=inherit
StandardError=inherit
Restart=always
User=<replace_username>

[Install]
WantedBy=multi-user.target
  • Reload systemd: sudo systemctl daemon-reload
  • Enable the service: sudo systemctl enable myscript.service
  • Start the service: sudo systemctl start myscript.service
  • To check the service status: sudo systemctl status myscript.service

Option 3: Autostart using lxsession

  • Edit the autostart configuration file: nano ~/.config/lxsession/LXDE-pi/autostart
  • Add the following line to automatically start the Python script: @lxterminal -e python3 /path/to/your/script.py
  • Save the file and initiate a system reboot: sudo reboot