I am trying to get my pi to open a terminal and run a python script when it boots up. I have followed the instructions of some guides and have so far been unsuccessful.
I have made a pythonfile called testfile.py located in /home/pi/Documents/testfile.py The contents are as follows
print('hello') input('press any key to exit')
I have added a file called testfile.desktop to /home/pi/.config/autostart/testfile.desktop. The contents are as follows
[Desktop Entry] Type=Application Name=testfile Hidden=false NoDisplay=false Terminal=true X-GNOME-Autostart-enabled=true Exec=/usr/bin/python3/home/pi/Documents/testfile.py
When i double click this file, the terminal opens and the python script runs as expected, but when i reboot the raspberry the script doesn’t run.
I duplicated what you did using an up-to-date Raspbian Buster in a Pi 4 B. (I wish all questions were as clear and complete as yours!)
Double-clicking the file on my machine brought up the
thonny IDE. (Note: The ‘any’ key doesn’t work because
input() needs an
enter to complete.) On reboot, I observed the same result you did. However, installing
xterm and changing the
Exec line to
Exec=xterm -hold -e '/usr/bin/python3 /home/pi/Documents/testfile.py'
causes an xterm window to open and the Python program to run. I was following
So, there is some interaction I don’t understand between autostart, Python, and terminal. Perhaps you could try a Python program that leaves some evidence in the file system, such as writing a tiny output file.
Edit: See this answer which appears to be more useful than mine.
Create a file:
Put all lines below there:
[Unit] Description=testfile service [Service] ExecStart=/usr/bin/python /home/pi/Documents/testfile.py StandardOutput=syslog StandardError=syslog Restart=on-failure User=root Group=root SyslogIdentifier=testfile [Install] WantedBy=multi-user.target
Save the file and reload the daemon:
sudo systemctl daemon-reload
Test that is your code is running:
sudo service testfile start
Check the log by:
journalctl -f -u testfile.service
It will give you the real-time log of your python code to troubleshoot what’s going on.
If everything was good as you intended, run this command to enable is as a startup service:
sudo systemctl enable testfile.service