User avatar
Frollo
Posts: 33
Joined: Thu Aug 27, 2015 8:44 pm

Run a script .py as a service

Sun Nov 12, 2017 3:47 pm

Hi everybody,

I have some Pi2 and Pi3 which communicate with python scripts.
As i need these scripts to automatically restart if needed, i try to start the scripts as a service on each Pi and then to start and stop the service in crontab.

I followed the help below to "start a python script as service" :
http://www.diegoacuna.me/how-to-run-a-s ... an-jessie/

-
My service is in /systemd/system.... It is named pymotion.service.

My problems are twice :
- the script run at "/" point, i would like it runs where the script is ("/media/pi/USB/pyde motion/171106 pyde_motion.py"), because it runs with files and numerous relatives paths.
- if i enable the service, it will start on boot (?), then i added in crontab to stop it on system start. Is it correct ? (i'm not sure if it will not start after)

Code: Select all

[Unit]
Description=PyDemon Motion ALPR
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python "/media/pi/USB/pyde motion/171106 pyde_motion.py"
RootDirectory="/media/pi/USB/pyde motion"		# this command doesn't work !!!!!!!!!!!!!!!!!!!!?
WorkingDirectory="/media/pi/USB/pyde motion"		# this command doesn't work !!!!!!!!!!!!!!!!!!!!?
Restart=on-abort

[Install]
WantedBy=mutli-user.target

Code: Select all

# crontab to specify when to run the script as a service
@reboot sudo systemctl stop pymotion.service
50 6 * * * sudo systemctl start pymotion.service
45 16 * * * sudo systemctl stop pymotion.service
:roll: maybe i'm not far from success ! :D

Skyway
Posts: 19
Joined: Sun Dec 27, 2015 8:26 pm

Re: Run a script .py as a service

Mon Nov 13, 2017 4:35 pm

Code: Select all

[Service]
Type=simple
ExecStart=/usr/bin/python "/media/pi/USB/pyde! !motion/171106! !pyde_motion.py"
RootDirectory="/media/pi/USB/pyde! !motion"		# this command doesn't work !!!!!!!!!!!!!!!!!!!!?
WorkingDirectory="/media/pi/USB/pyde! !motion"		# this command doesn't work !!!!!!!!!!!!!!!!!!!!?
I don't know how the code looks, but empty spaces i think must be escaped with \
Kinda like this:

Code: Select all

RootDirectory="/media/pi/USB/pyde\  motion"	
Also you can run command directly from cli:

Code: Select all

/usr/bin/python /media/pi/USB/pyde\ motion/171106\ pyde_motion.py
and check if that works!

User avatar
Frollo
Posts: 33
Joined: Thu Aug 27, 2015 8:44 pm

Re: Run a script .py as a service

Tue Nov 14, 2017 9:15 am

For instance, it works only with Idle+F5, and direct execution on the script.
Same problem in terminal below, this command is run at "/" but not at the script location :

Code: Select all

/usr/bin/python "/media/pi/USB/pyde_motion/171106 pyde_motion.py"
In the declaration of the daemon, i tested :

Code: Select all

RootDirectory="/media/pi/USB/pyde\  motion"
 # or
RootDirectory="/media/pi/USB/pyde\  motion/"
 # or
RootDirectory="/media/pi/USB/pyde_motion/"
 #or
WorkingDirectory="/media/pi/USB/pyde_motion/"
RootDirectory="/media/pi/USB/pyde_motion/"
RootImage="/media/pi/USB/pyde_motion/"
But dosen't work, still executed at the "/"... :? I think the "space" is not the problem, but it the script executed par the system has to be informed that we want to have ti executed at the script location. That's why even executed in terminal "sudo python /media/..." doesn't work.
(I need to succed running it by a service, because that way i could start and stop it at any time, and "on-abort" it will restart..)

If we can't find the solution, of course i can modify at the beginning of the script a path test, and a "cd ...", but my script may not be still portable (Win/Linux, and Pi2 Pi3) as it is today...

User avatar
Frollo
Posts: 33
Joined: Thu Aug 27, 2015 8:44 pm

Re: Run a script .py as a service

Sat Dec 16, 2017 6:35 pm

I succeed ! :D

with this tutorial :


First of all, we are going to write a small python script which print "Hello World" every 60 seconds. This is going to be our service script (hello_world.py):

Code: Select all

 #!/usr/bin/python
 
from time import sleep

try:
    while True:
        print "Hello World"
        sleep(60)
except KeyboardInterrupt, e:
    logging.info("Stopping...")

You can execute it by python hello_world.py. If you get boring reading so many hello worlds, press Ctrl+C (or Cmd+C on OSX) to stop it. Save this file as hello_world.py in your home folder (home/pi/). Now we're going to define the service to run this script:

Code: Select all

cd /lib/systemd/system/
sudo nano hello.service


The service definition must be on the /lib/systemd/system folder. Our service is going to be called "hello.service":

Code: Select all

[Unit]
Description=Hello World
After=multi-user.target
 
[Service]
Type=simple
ExecStart=/usr/bin/python /home/pi/hello_world.py
Restart=on-abort
 
[Install]
WantedBy=multi-user.target

Here we are creating a very simple service that runs our hello_world script and if by any means is aborted is going to be restarted automatically. You can check more on service's options in the next wiki: https://wiki.archlinux.org/index.php/systemd.

Now that we have our service we need to activate it:

Code: Select all

sudo chmod 644 /lib/systemd/system/hello.service
chmod +x /home/pi/hello_world.py
sudo systemctl daemon-reload
sudo systemctl enable hello.service
sudo systemctl start hello.service


sudo chmod 644 /lib/systemd/system/hello.service
chmod +x /home/pi/hello_world.py
sudo systemctl daemon-reload
sudo systemctl enable hello.service
sudo systemctl start hello.service


For every change that we do on the /lib/systemd/system folder we need to execute a daemon-reload (third line of previous code). If we want to check the status of our service, you can execute:

Code: Select all

sudo systemctl status hello.service

In general:

Code: Select all

# Check status
sudo systemctl status hello.service

# Start service
sudo systemctl start hello.service

# Stop service
sudo systemctl stop hello.service

# Check service's log
sudo journalctl -f -u hello.service

User avatar
DougieLawson
Posts: 42641
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK

Re: Run a script .py as a service

Sat Dec 16, 2017 7:38 pm

Don't put user services in /lib/systemd. User defined services should go in /etc/systemd/system.
Languages using left-hand whitespace for syntax are ridiculous

DMs sent on https://twitter.com/DougieLawson or LinkedIn will be answered next month.
Fake doctors - are all on my foes list.

The use of crystal balls and mind reading is prohibited.

Ghwana
Posts: 77
Joined: Mon Nov 13, 2017 12:04 pm

Re: Run a script .py as a service

Wed Mar 14, 2018 11:39 am

Hi Dougie, I've enjoyed following some of your responses on these forums, I was hoping you could help me.

I'm looking from a python code to start a .py for 5 seconds, then stopping it for 1 seconds, restarting it again for 5 seconds and so on , in a loop?

Cheers Ghwana

User avatar
DougieLawson
Posts: 42641
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK

Re: Run a script .py as a service

Wed Mar 14, 2018 3:06 pm

Ghwana wrote:
Wed Mar 14, 2018 11:39 am
Hi Dougie, I've enjoyed following some of your responses on these forums, I was hoping you could help me.

I'm looking from a python code to start a .py for 5 seconds, then stopping it for 1 seconds, restarting it again for 5 seconds and so on , in a loop?

Cheers Ghwana
Don't do that. Use a time.sleep(5) loop in your code. It will take more than 5 seconds to get a new task running.
Languages using left-hand whitespace for syntax are ridiculous

DMs sent on https://twitter.com/DougieLawson or LinkedIn will be answered next month.
Fake doctors - are all on my foes list.

The use of crystal balls and mind reading is prohibited.

Ghwana
Posts: 77
Joined: Mon Nov 13, 2017 12:04 pm

Re: Run a script .py as a service

Wed Mar 14, 2018 4:54 pm

Thank you for your comment, I was hoping to achieve to same as manually stopping the code on LXterminal with Ctrl+c and then restarting it again by reinstating it sudo python scrpt.py enter. Is there a way of doing this with a python script, I've been looking at different forums and subprocess has been used, but not sure if this will work. The example is using a button to stop and start the .py.

I was hoping there was a way of writing a script that can stop and start .py without a button.

User avatar
DougieLawson
Posts: 42641
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK

Re: Run a script .py as a service

Thu Mar 15, 2018 1:24 am

You can't easily do it faster than once a minute. You also have to work hard to stop more than one copy of your script running.

Doing it with a time.sleep() loop is orders of magnitude easier.
Languages using left-hand whitespace for syntax are ridiculous

DMs sent on https://twitter.com/DougieLawson or LinkedIn will be answered next month.
Fake doctors - are all on my foes list.

The use of crystal balls and mind reading is prohibited.

Sdack
Posts: 6
Joined: Tue Nov 07, 2017 6:54 am

Re: Run a script .py as a service

Thu Aug 09, 2018 4:17 am

Hi guys (and gals)
,
I have a bash script running, on a few Raspberry Pi's controlling some time-lapse camera rigs and as I deploy more of these units, I'm looking to upgrade the script startup, from a once-a-day cron job, which doesn't restart if there's any interruption ie. a power failure.

I am looking for an alternative that will either sense if my script has stopped, or at least regularly check if it's still running and, if not, restart it.

I'm not sure the "hello world" example would work in my case, as there doesn't seem to be any checking for existing processes.

Any suggestion would be appreciated

Sdack

DirkS
Posts: 10882
Joined: Tue Jun 19, 2012 9:46 pm
Location: Essex, UK

Re: Run a script .py as a service

Thu Aug 09, 2018 4:44 am

Use a systemd service file and e.g.

Code: Select all

Restart=always
to the Unit section.
There are many examples here on the forum and elsewhere.

Return to “Python”