How to make a raspberry pi script run up on startup
Step 1
Open your terminal and write “crontab -e”, when opened for the first time an editor needs to be selected. For this example we choose nano.
Step 2
After opening nano navigate down to the bottom of the document. Here you will need to write "@reboot python3 " followed by the directory your file is located. If your following this tutorial using nano, you can press ctrl+x to exit the editor, then press ‘y’ to save the edit.
Example
Start a new script and copy the following code
import os from datetime import datetime import time MAX_FILE_SIZE_B = 1024 def log_current_time(log_path): now = datetime.now() timestamp = now.strftime('%Y-%m-%d_%H-%M-%S') write_mode = 'a' if os.path.isfile(log_path): size = os.path.getsize(log_path) if size >= MAX_FILE_SIZE_B: write_mode = 'w' with open(log_path, mode=write_mode) as output_file: output_file.write(timestamp + '\n') print(timestamp) if __name__ == '__main__': log_path = '/home/pi/Desktop/output.txt' while True: log_current_time(log_path) time.sleep(1.0)
Follow the the previous mentioned steps to setup the to start upon boot up.
Now restart the Raspberry pi and navigate to your Destop folder in your files.
Open the file named “output.txt”
Here you will see the current date and time.
Extra
To stop running a script up on bootup, open the crontab. Just remove the line with your script, then close and save the editor. Don’t forget to restart the Raspberry pi.