- alexeames
- Forum Moderator
- Posts: 2874
- Joined: Sat Mar 03, 2012 11:57 am
- Location: UK
- Contact: Website
Best way to run a python script at startup?
Not sure where to post this as it covers several topic areas.
Basically I've been writing a script for my autonomous RasPiCamCorder, which I want to run at startup. It works OK running it as "sudo python scriptname.py" at the end of /etc/rc.local
Except... It suppresses the tty console login on the UART ports.
I think maybe it's running too soon in the startup process or something? The startup messages in the UART console stop somewhere around the i2c setup part.
If I comment out that line of rc.local, the console login appears and works fine. But I need both the script and the console active at once.
So. Is there another way? I know there are other "better" ways (something like init.d?) but it's slightly unfamiliar territory, so I thought I'd ask. Is there a way to delay the running of the script in rc.local? Or is there an altogether better way to achieve this?
Basically I've been writing a script for my autonomous RasPiCamCorder, which I want to run at startup. It works OK running it as "sudo python scriptname.py" at the end of /etc/rc.local
Except... It suppresses the tty console login on the UART ports.
I think maybe it's running too soon in the startup process or something? The startup messages in the UART console stop somewhere around the i2c setup part.
If I comment out that line of rc.local, the console login appears and works fine. But I need both the script and the console active at once.
So. Is there another way? I know there are other "better" ways (something like init.d?) but it's slightly unfamiliar territory, so I thought I'd ask. Is there a way to delay the running of the script in rc.local? Or is there an altogether better way to achieve this?
Alex Eames RasPi.TV, RasP.iO
Re: Best way to run a python script at startup?
"sudo python scriptname.py"
you forgot the & at the end of that.
You could make your /etc/rc.local look like this:
/yourpath/bin/yourscript.sh &
Then in yourscript.sh put:
#!/bin/sh
sleep 10
sudo python scriptname.py
you forgot the & at the end of that.
You could make your /etc/rc.local look like this:
/yourpath/bin/yourscript.sh &
Then in yourscript.sh put:
#!/bin/sh
sleep 10
sudo python scriptname.py
Antikythera
- alexeames
- Forum Moderator
- Posts: 2874
- Joined: Sat Mar 03, 2012 11:57 am
- Location: UK
- Contact: Website
Re: Best way to run a python script at startup?
Thanks. I'll try backgrounding it first and see if that does it on its own. 
A combination of your suggestions was effective. I used the bash script with a sleep AND backgrounded the python program. It now works as I want it to. I can log in via a bluetooth serial adaptor if something goes wrong AND have the program up and running by default.
I'm still open to other suggestions if there is a "better" way, but this works so far.

A combination of your suggestions was effective. I used the bash script with a sleep AND backgrounded the python program. It now works as I want it to. I can log in via a bluetooth serial adaptor if something goes wrong AND have the program up and running by default.
I'm still open to other suggestions if there is a "better" way, but this works so far.

Alex Eames RasPi.TV, RasP.iO
Re: Best way to run a python script at startup?
I take credit cards, paypal, personal checks, and cash.
Antikythera
Re: Best way to run a python script at startup?
You don't need sudo.
Everything in /etc/rc.local runs as the root user.
Also, you can group commands together using ().
The following should work in /etc/rc.local
The () make both commands run in the background.
Everything in /etc/rc.local runs as the root user.
Also, you can group commands together using ().
The following should work in /etc/rc.local
Code: Select all
(sleep 10;python scriptname.py)&
- alexeames
- Forum Moderator
- Posts: 2874
- Joined: Sat Mar 03, 2012 11:57 am
- Location: UK
- Contact: Website
Re: Best way to run a python script at startup?
Excellent. Thanksrpdom wrote:You don't need sudo.
Everything in /etc/rc.local runs as the root user.
Also, you can group commands together using ().
The following should work in /etc/rc.localThe () make both commands run in the background.Code: Select all
(sleep 10;python scriptname.py)&

Alex Eames RasPi.TV, RasP.iO
- MattHawkinsUK
- Posts: 538
- Joined: Tue Jan 10, 2012 8:48 pm
- Location: UK
- Contact: Website
Re: Best way to run a python script at startup?
You could use the @reboot option in Cron. I've used this to run scripts on boot and it works ok. Not quite sure where in the boot sequence this occurs but it is worth a try. Also much easier to add a line to Crontab rather than editing other files.
My Raspberry Pi blog and home of the BerryClip Add-on board : http://www.raspberrypi-spy.co.uk/
Follow me on Google+, Facebook, Pinterest and Twitter (@RPiSpy)
Follow me on Google+, Facebook, Pinterest and Twitter (@RPiSpy)
- LetHopeItsSnowing
- Posts: 357
- Joined: Sat May 26, 2012 6:40 am
- Location: UK
- Contact: Website
Re: Best way to run a python script at startup?
Alex,
I would use an init.d script. You can specify in the header where in the boot cycle you want it to start, in your case right at the end.
See my blog for instructions.
http://www.stuffaboutcode.com/2012/06/r ... rt-up.html
Modify the Required-Start tag in the LSB header, you should be able to add $all to the tag (after $syslog) which tells the script to run after all other scripts.
See http://wiki.debian.org/LSBInitScripts for more info.
Mart
I would use an init.d script. You can specify in the header where in the boot cycle you want it to start, in your case right at the end.
See my blog for instructions.
http://www.stuffaboutcode.com/2012/06/r ... rt-up.html
Modify the Required-Start tag in the LSB header, you should be able to add $all to the tag (after $syslog) which tells the script to run after all other scripts.
See http://wiki.debian.org/LSBInitScripts for more info.
Mart
"am I getting slower, or is stuff more complicated; either way I now have to write it down - stuffaboutcode.com"
Re: Best way to run a python script at startup?
I am having some trouble with cron and rc.local
I think it may be something to do with my application.
This is my first ever electronics project and I have no programming experience so I may be making some noob error.
I have the RPi connected to an MPR121. It is detecting12 inputs and triggering sounds (via pygame mixer) and lights (sends serial triggers via USB to an homemade arduino which runs one of three sequences on an LED strip).
When it works normally (from the command line) I get reports of the input that was touched in the command line.
It prints
input 1 was touched
input 1 was released
etc
until I use a keyboard interrupt.
The script is a python script runs from the command line with
sudo python home/pi/beetbox_serial.py
However if I put this command into cron or rc.local the behaviour is strange
For etc/rc.local I tried
(sleep 10; python /home/pi/beetbox_serial.py)
I tried this with & at the end and without & at the end
By strange I mean- it detects inputs, but doesn't print the report. The serial communication works (lights work on inputs 0-2) but the pygame sounds don't (inputs 3-11). There is definite detection of the inputs 3-11 as there is a pop through the speaker, but it doesn't trigger the correct sounds.
The same happens if I use the shell script example above.
The shell script is called launch_script.sh
When I run it from the command line with /home/pi/launch_script.sh
it works. When I put it in /etc/rc.local then it just pops. Very confusing
Also I can't just kill the process. If I use ps aux | grep python to find the PID and try sudo kill 2123 (using the correct PID) it doesn't kill it.
I have to use the (bad form) sudo kill -9 2123
If I do kill -9 it and then in the command line type
sudo python /home/pi/beetbox_serial.py
Then it works normally.
What I am trying to do is launch the program at 07:30 so my son can use it all day, then kill it at 20:00 so he can't play drum and voice samples all night long. I was actually going to launch a lights only version at 20:05 so he can have the LED's as night lights. I would settle for just being able to launch and then kill it.
Happy to post the whole code if necessary (not sure if it'll be useful or not)
Thanks
Shane
I think it may be something to do with my application.
This is my first ever electronics project and I have no programming experience so I may be making some noob error.
I have the RPi connected to an MPR121. It is detecting12 inputs and triggering sounds (via pygame mixer) and lights (sends serial triggers via USB to an homemade arduino which runs one of three sequences on an LED strip).
When it works normally (from the command line) I get reports of the input that was touched in the command line.
It prints
input 1 was touched
input 1 was released
etc
until I use a keyboard interrupt.
The script is a python script runs from the command line with
sudo python home/pi/beetbox_serial.py
However if I put this command into cron or rc.local the behaviour is strange
For etc/rc.local I tried
(sleep 10; python /home/pi/beetbox_serial.py)
I tried this with & at the end and without & at the end
By strange I mean- it detects inputs, but doesn't print the report. The serial communication works (lights work on inputs 0-2) but the pygame sounds don't (inputs 3-11). There is definite detection of the inputs 3-11 as there is a pop through the speaker, but it doesn't trigger the correct sounds.
The same happens if I use the shell script example above.
The shell script is called launch_script.sh
When I run it from the command line with /home/pi/launch_script.sh
it works. When I put it in /etc/rc.local then it just pops. Very confusing
Also I can't just kill the process. If I use ps aux | grep python to find the PID and try sudo kill 2123 (using the correct PID) it doesn't kill it.
I have to use the (bad form) sudo kill -9 2123
If I do kill -9 it and then in the command line type
sudo python /home/pi/beetbox_serial.py
Then it works normally.
What I am trying to do is launch the program at 07:30 so my son can use it all day, then kill it at 20:00 so he can't play drum and voice samples all night long. I was actually going to launch a lights only version at 20:05 so he can have the LED's as night lights. I would settle for just being able to launch and then kill it.
Happy to post the whole code if necessary (not sure if it'll be useful or not)
Thanks
Shane
Re: Best way to run a python script at startup?
Hello Shanester,
If you use absolute paths for your .wav files, I think it will clear up your problem; at least it worked for me.
Until I did that, pygame wouldn't play my sound files.
Examples for the two steps I took....
in your scriptfile:
kick = pygame.mixer.Sound('/home/pi/samples/kick.wav')
in /etc/:
"sudo chmod 755 rc.local" to make rc.local read/write/exe priv.
Then just above "exit 0" in rc.local, add the following:
(sleep 10;sudo python /home/pi/folder/yourscript.py) &
good luck,
N8HWV
If you use absolute paths for your .wav files, I think it will clear up your problem; at least it worked for me.
Until I did that, pygame wouldn't play my sound files.
Examples for the two steps I took....
in your scriptfile:
kick = pygame.mixer.Sound('/home/pi/samples/kick.wav')
in /etc/:
"sudo chmod 755 rc.local" to make rc.local read/write/exe priv.
Then just above "exit 0" in rc.local, add the following:
(sleep 10;sudo python /home/pi/folder/yourscript.py) &
good luck,
N8HWV
Re: Best way to run a python script at startup?
not trying to hi-jack your thread,but are you having the problem where after it executes the .py the cmd prompt still appears?
i just have a simple menu that boots after i log in. but after the 'exit' option there's pi@raspberrypi ~ $ and it won't let me select any of the options of the menu.
kyle
i just have a simple menu that boots after i log in. but after the 'exit' option there's pi@raspberrypi ~ $ and it won't let me select any of the options of the menu.
kyle
Re: Best way to run a python script at startup?
Hi,
Thanks for the replies.
I wondered if it was something to do with the Pygame setup so ran an autologin at boot as user Pi, then used Pi's Crontab rather than sudo crontab and it all worked. I might also look at the above solution.
All the best
Shane
Thanks for the replies.
I wondered if it was something to do with the Pygame setup so ran an autologin at boot as user Pi, then used Pi's Crontab rather than sudo crontab and it all worked. I might also look at the above solution.
All the best
Shane
Re: Best way to run a python script at startup?
I am trying to run a python code which should run after boot up (it has GUI )
1) should we use" #!/usr/bin/env python "in the python script
2)where should we save the script
3)how /etc/rc.local script work
4)tutorials to create debian file
1) should we use" #!/usr/bin/env python "in the python script
2)where should we save the script
3)how /etc/rc.local script work
4)tutorials to create debian file
- PangolinPaws
- Posts: 89
- Joined: Wed Mar 05, 2014 9:04 pm
- Location: Wiltshire, UK
- Contact: Website
Re: Best way to run a python script at startup?
I'm glad I found this thread, your suggestion worked perfectly. However I've noticed that pressing Ctrl+C doesn't seem to work when I run my script using this method.LetHopeItsSnowing wrote:Alex,
I would use an init.d script. You can specify in the header where in the boot cycle you want it to start, in your case right at the end.
See my blog for instructions.
http://www.stuffaboutcode.com/2012/06/r ... rt-up.html
Modify the Required-Start tag in the LSB header, you should be able to add $all to the tag (after $syslog) which tells the script to run after all other scripts.
See http://wiki.debian.org/LSBInitScripts for more info.
Mart
My program contains the helpful...
Code: Select all
try:
X
except KeyboardInterrupt:
Y
https://github.com/PangolinPaw
Re: Best way to run a python script at startup?
Your program runs as service / daemon and it cannot use the normal I/O (keyboard, etc)PangolinPaws wrote:...thing and works when I run it from the terminal, but not when it starts on boot. Does anyone know why this is or how I can correct it?
The blog you link to shows how to start / stop your program.
Gr.
Dirk.
- PangolinPaws
- Posts: 89
- Joined: Wed Mar 05, 2014 9:04 pm
- Location: Wiltshire, UK
- Contact: Website
Re: Best way to run a python script at startup?
Ah, I see... I was actually using (probably incorrectly) the KeyboardInterrupt to exit a loop and return to a 'main menu'. Something along the lines of:Your program runs as service / daemon and it cannot use the normal I/O (keyboard, etc)
The blog you link to shows how to start / stop your program.
Code: Select all
try:
#Menu stuff goes here
while True:
# This loops until Ctrl+C is pressed
try:
time.sleep(5)
except KeyboardInterrupt:
break
except KeyboardInterrupt:
#Exit program
https://github.com/PangolinPaw
- Nfarrow
- Posts: 48
- Joined: Sat Dec 20, 2014 1:24 am
- Location: Oklahoma, USA
- Contact: Website Facebook Twitter YouTube
Re: Best way to run a python script at startup?
For people like myself who learn by watching rather than reading.
https://youtu.be/vHPsAg8cmIg
https://youtu.be/vHPsAg8cmIg
Twitter: @farrownick
Instagram veggievampire
I own a lot of Pis....
Instagram veggievampire
I own a lot of Pis....
Re: Best way to run a python script at startup?
For me, this was a little complicated. I didn't know anything about bash scripting, so it was way easier just to type a command in the /etc/rc.local file.LetHopeItsSnowing wrote:Alex,
I would use an init.d script. You can specify in the header where in the boot cycle you want it to start, in your case right at the end.
See my blog for instructions.
http://www.stuffaboutcode.com/2012/06/r ... rt-up.html
Modify the Required-Start tag in the LSB header, you should be able to add $all to the tag (after $syslog) which tells the script to run after all other scripts.
See http://wiki.debian.org/LSBInitScripts for more info.
Mart
Kratos
I have posted mostly with a Pi 2 running either Ubuntu MATE, or Raspbian.
- alexeames
- Forum Moderator
- Posts: 2874
- Joined: Sat Mar 03, 2012 11:57 am
- Location: UK
- Contact: Website
Re: Best way to run a python script at startup?
Since Jessie, I've been using the instructions by Matt Hawkins here...Kratos wrote:For me, this was a little complicated. I didn't know anything about bash scripting, so it was way easier just to type a command in the /etc/rc.local file.LetHopeItsSnowing wrote:Alex,
I would use an init.d script. You can specify in the header where in the boot cycle you want it to start, in your case right at the end.
See my blog for instructions.
http://www.stuffaboutcode.com/2012/06/r ... rt-up.html
Modify the Required-Start tag in the LSB header, you should be able to add $all to the tag (after $syslog) which tells the script to run after all other scripts.
See http://wiki.debian.org/LSBInitScripts for more info.
Mart
Kratos
http://www.raspberrypi-spy.co.uk/2015/1 ... g-systemd/
Alex Eames RasPi.TV, RasP.iO
Re: Best way to run a python script at startup?
With Jessie I found that starting automatically as an user process is best to set up the start in /etc/xdg/autostart/myscript.desktop
Then you already have the desktop up and running.
The file myscript.desktop could have a content like this:
Then you already have the desktop up and running.
The file myscript.desktop could have a content like this:
Code: Select all
[Desktop Entry]
Type=Application
Name=myscript.py
Comment=Start my script
NoDisplay=false
Exec=python /home/pi/myscript.py
NotShowIn=GNOME;KDE;XFCE;
Name[en_US]=myscript.py
Re: Best way to run a python script at startup?
Of course that only works if you actually boot directly to the desktop...karrika wrote:With Jessie I found that starting automatically as an user process is best to set up the start in /etc/xdg/autostart/myscript.desktop
Re: Best way to run a python script at startup?
Which is the case if you want to run code with a GUI.DirkS wrote:Of course that only works if you actually boot directly to the desktop...karrika wrote:With Jessie I found that starting automatically as an user process is best to set up the start in /etc/xdg/autostart/myscript.desktop
Re: Best way to run a python script at startup?
I'm trying to run a script on a Pi 0 at boot time and I cannot get it to work with any method I have seen posted. I have tried the crontab -e; the init.d and the rc.local methods and it doesn't run. I have a Pi 3 using the the same command via the rc.local method and it works as I want. The versions of the Pi3 is:
Linux PiGMi 4.1.19-v7+ #858 SMP Tue Mar 15 15:56:00 GMT 2016 armv7l GNU/Linux
and the Pi0 is:
Linux pi0 4.4.11+ #888 Mon May 23 20:02:58 BST 2016 armv6l GNU/Linux
This is the rc.local command:
sudo python /home/pi/PiGMiMon.py &
The only difference in the program file is on the Pi3 it is owned by pi, but on the Pi0 it is owned by www-data. I need that permissions setting to access a web file. On the Pi3 I'm using an older version of Apache and it worked just as created.
Any clues where I may have made a mistake or what is different enough about a Pi 0 that I need to do?
Linux PiGMi 4.1.19-v7+ #858 SMP Tue Mar 15 15:56:00 GMT 2016 armv7l GNU/Linux
and the Pi0 is:
Linux pi0 4.4.11+ #888 Mon May 23 20:02:58 BST 2016 armv6l GNU/Linux
This is the rc.local command:
sudo python /home/pi/PiGMiMon.py &
The only difference in the program file is on the Pi3 it is owned by pi, but on the Pi0 it is owned by www-data. I need that permissions setting to access a web file. On the Pi3 I'm using an older version of Apache and it worked just as created.
Any clues where I may have made a mistake or what is different enough about a Pi 0 that I need to do?
- johnb_summers
- Posts: 285
- Joined: Thu Aug 04, 2016 7:48 pm
- Location: Bushey UK
Re: Best way to run a python script at startup?
I run a python script at boot, it has a try loop at the start to wait until the MySQL server is running, when it is it waits a further 10 seconds and by then every thing is running, I use cron at boot to run it, it works perfectly for me every time, I have found if you try to get any data from anything that is not running then you script will crash without telling you, but once everything is running it never crashes.
all my code in python and PHP uses the MySQL server so its a must it has to be running.
all my code in python and PHP uses the MySQL server so its a must it has to be running.
MyPi Developer
http://mypiworld.com/
http://mypi.tech/
https://www.youtube.com/watch?v=US2nyRgg-SY&nohtml5=False
http://mypiworld.com/
http://mypi.tech/
https://www.youtube.com/watch?v=US2nyRgg-SY&nohtml5=False
- DougieLawson
- Posts: 40469
- Joined: Sun Jun 16, 2013 11:19 pm
- Location: A small cave in deepest darkest Basingstoke, UK
- Contact: Website Twitter
Re: Best way to run a python script at startup?
Use a systemd service file. You can force it to wait until MySQL is running.
that example waits for both Mosquitto and MariaDB (aka MySQL).
Code: Select all
[Unit]
Description=PHP SQL server
After=mosquitto.service mysql.service
[Service]
ExecStart=/usr/local/bin/some_such_pgm.php
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier=SQL_PHP_service
User=pi
Group=pi
[Install]
WantedBy=multi-user.target
Any language using left-hand whitespace for syntax is ridiculous
Any DMs sent on Twitter will be answered next month.
Fake doctors - are all on my foes list.
Any requirement to use a crystal ball or mind reading will result in me ignoring your question.
Any DMs sent on Twitter will be answered next month.
Fake doctors - are all on my foes list.
Any requirement to use a crystal ball or mind reading will result in me ignoring your question.