tinus88
Posts: 3
Joined: Mon Jan 07, 2013 2:57 pm

Python script as service/autorun

Mon Jan 07, 2013 3:08 pm

Hello,

I would like to introduce myself, I am Tinus.
Fairly new to python, very new to linux.

I made a python script, which uses some mysql and UDP connections.
I managed to get it to run at boot of the raspi, following this tutorial:
http://www.stuffaboutcode.com/2012/06/r ... rt-up.html

It works as described, but in my python script I print some text to the terminal.
When the Pi boots, it eventually starts my python script but then it is impossible to log in to cmd.
I have to log in by using ssh.

What I would like is that the python script runs invisible at boot-up.
Like it is a service.
Does anyone know how to do this?

Greetings,

Tinus

User avatar
bgreat
Posts: 235
Joined: Mon Jan 23, 2012 2:09 pm

Re: Python script as service/autorun

Mon Jan 07, 2013 5:22 pm

Not certain of how you are starting your application, but the simplest solution is to run it in the background.

If you are doing:

Code: Select all

python myscript.py
Instead, do:

Code: Select all

python myscript.py &
The '&' at the end of a command runs it as a background process, returning control to the terminal.

If you want to capture the output of your script for later viewing, you can send it to a file using output redirection:

Code: Select all

python myscript.py >/tmp/script_stdout.txt 2>/tmp/script_stderr.txt &
This will send "error" messages to the /tmp/script_stderr.txt file and "normal" messages to the /tmp/script_stdout.txt file.

If you want to send both outputs to the same file, you can use this format:

Code: Select all

python myscript.py >/tmp/script_stdout.txt 2>&1 &
The '&1' argument for the second redirection, says to use file descriptor "1" as the destination which is the '>' redirection destination.

FYI: File descriptor "1" is "stdout". File descriptor "2" is "stderr". File descriptor "0" is "stdin".

Enjoy!
Bill

tinus88
Posts: 3
Joined: Mon Jan 07, 2013 2:57 pm

Re: Python script as service/autorun

Mon Jan 07, 2013 9:41 pm

Oh wow! Thanks, is it really that simple?
I will try this tomorrow!
Thank you in advance.

Bergschreck
Posts: 11
Joined: Tue Jan 01, 2013 7:41 am

Re: Python script as service/autorun

Wed Feb 13, 2013 1:08 pm

You should make your script a daemon using python-daemon:
http://www.python.org/dev/peps/pep-3143/

Then start it through a debian init script:
http://wiki.debian.org/LSBInitScripts

User avatar
ReadiesCards
Posts: 40
Joined: Sun May 13, 2012 5:22 am

Re: Python script as service/autorun

Sun Mar 17, 2013 7:33 am

Many thanks bgreat very useful

Shame the & is not something more searchable like 'background'

Return to “Python”