Best way to run a python script at startup?


34 posts   Page 1 of 2   1, 2
by alexeames » Tue Jun 04, 2013 4:38 pm
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?
Alex Eames RasPi.TV, RasP.iO
User avatar
Forum Moderator
Forum Moderator
Posts: 2806
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
by solar3000 » Tue Jun 04, 2013 5:37 pm
"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
User avatar
Posts: 947
Joined: Sat May 18, 2013 12:14 am
by alexeames » Tue Jun 04, 2013 6:27 pm
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. :D
Alex Eames RasPi.TV, RasP.iO
User avatar
Forum Moderator
Forum Moderator
Posts: 2806
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
by solar3000 » Tue Jun 04, 2013 8:21 pm
I take credit cards, paypal, personal checks, and cash.
Antikythera
User avatar
Posts: 947
Joined: Sat May 18, 2013 12:14 am
by rpdom » Wed Jun 05, 2013 6:02 am
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
Code: Select all
(sleep 10;python scriptname.py)&

The () make both commands run in the background.
User avatar
Posts: 10577
Joined: Sun May 06, 2012 5:17 am
Location: Essex, UK
by alexeames » Wed Jun 05, 2013 6:24 am
rpdom 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.local
Code: Select all
(sleep 10;python scriptname.py)&

The () make both commands run in the background.


Excellent. Thanks :)
Alex Eames RasPi.TV, RasP.iO
User avatar
Forum Moderator
Forum Moderator
Posts: 2806
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
by MattHawkinsUK » Wed Jun 05, 2013 9:28 am
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)
User avatar
Posts: 531
Joined: Tue Jan 10, 2012 8:48 pm
Location: UK
by LetHopeItsSnowing » Wed Jun 05, 2013 7:59 pm
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/raspberry-pi-run-program-at-start-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"
User avatar
Posts: 322
Joined: Sat May 26, 2012 6:40 am
Location: UK
by shanester » Mon Sep 16, 2013 5:32 pm
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
Posts: 14
Joined: Tue Sep 10, 2013 8:03 pm
by N8HWV » Thu Sep 26, 2013 5:06 am
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
Posts: 7
Joined: Fri Mar 29, 2013 6:16 pm
Location: Green Bay
by fawked » Sat Sep 28, 2013 3:24 am
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
Posts: 15
Joined: Tue Aug 27, 2013 9:50 pm
by shanester » Sat Sep 28, 2013 8:30 am
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
Posts: 14
Joined: Tue Sep 10, 2013 8:03 pm
by ashwin8 » Tue Nov 19, 2013 10:38 am
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
Posts: 2
Joined: Tue Nov 19, 2013 9:56 am
by PangolinPaws » Tue Dec 23, 2014 12:11 pm
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/raspberry-pi-run-program-at-start-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'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.

My program contains the helpful...
Code: Select all
try:
    X
except KeyboardInterrupt:
    Y

...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?
https://github.com/PangolinPaw
User avatar
Posts: 88
Joined: Wed Mar 05, 2014 9:04 pm
Location: Wiltshire, UK
by DirkS » Tue Dec 23, 2014 12:45 pm
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?

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.

Gr.
Dirk.
Posts: 6698
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK
by PangolinPaws » Tue Dec 23, 2014 2:21 pm
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.


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:
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


I wanted the user to be presented with my menu (used to run a variety of things) and nothing else on boot. I'm sure there's a better way than the try/except pairs to do what I'm after, I just never needed to find it before now.
https://github.com/PangolinPaw
User avatar
Posts: 88
Joined: Wed Mar 05, 2014 9:04 pm
Location: Wiltshire, UK
by Nfarrow » Sun Jan 10, 2016 11:29 am
For people like myself who learn by watching rather than reading.
https://youtu.be/vHPsAg8cmIg
Twitter: @farrownick
Instagram veggievampire
I own a lot of Pis....
User avatar
Posts: 35
Joined: Sat Dec 20, 2014 1:24 am
Location: Oklahoma, USA
by Kratos » Sun Jan 10, 2016 3:16 pm
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/raspberry-pi-run-program-at-start-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


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.

Kratos
If it ain't fixed, break it till it is.
Most of my posts were posted using a Pi 2 running Ubuntu MATE 16.
User avatar
Posts: 379
Joined: Sun Apr 12, 2015 12:41 pm
by alexeames » Sun Jan 10, 2016 4:11 pm
Kratos wrote:
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/raspberry-pi-run-program-at-start-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


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.

Kratos


Since Jessie, I've been using the instructions by Matt Hawkins here...
http://www.raspberrypi-spy.co.uk/2015/1 ... g-systemd/
Alex Eames RasPi.TV, RasP.iO
User avatar
Forum Moderator
Forum Moderator
Posts: 2806
Joined: Sat Mar 03, 2012 11:57 am
Location: UK
by karrika » Sun Jan 10, 2016 4:20 pm
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:

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
User avatar
Posts: 849
Joined: Mon Oct 19, 2015 6:21 am
Location: Finland
by DirkS » Sun Jan 10, 2016 4:23 pm
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

Of course that only works if you actually boot directly to the desktop...
Posts: 6698
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK
by karrika » Sun Jan 10, 2016 5:14 pm
DirkS wrote:
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

Of course that only works if you actually boot directly to the desktop...


Which is the case if you want to run code with a GUI.
User avatar
Posts: 849
Joined: Mon Oct 19, 2015 6:21 am
Location: Finland
by robboz4 » Wed Sep 28, 2016 8:51 pm
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?
Posts: 11
Joined: Mon Feb 24, 2014 7:48 pm
by johnb_summers » Wed Sep 28, 2016 11:13 pm
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.
MyPi Developer
http://mypiworld.com/
http://mypi.tech/

https://www.youtube.com/watch?v=US2nyRgg-SY&nohtml5=False
User avatar
Posts: 287
Joined: Thu Aug 04, 2016 7:48 pm
Location: Bushey UK
by DougieLawson » Wed Sep 28, 2016 11:36 pm
Use a systemd service file. You can force it to wait until MySQL is running.

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
that example waits for both Mosquitto and MariaDB (aka MySQL).
Microprocessor, Raspberry Pi & Arduino Hacker
Mainframe database troubleshooter
MQTT Evangelist
Twitter: @DougieLawson

Since 2012: 1B*5, 2B*2, B+, A+, Zero*2, 3B*3

Please post ALL technical questions on the forum. Do not send private messages.
User avatar
Posts: 27549
Joined: Sun Jun 16, 2013 11:19 pm
Location: Basingstoke, UK