Python Forum
Issues with Python script as service
Thread Rating:
  • 1 Vote(s) - 5 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Issues with Python script as service
#1
Setup details:
RPI Version: Raspberry Pi 2 Model BV1.1
Python Version: 2.7

I have created a small program to control the fan and lights in my hydroponic room. I am using 8 channel relay board with external power supply. Everything works fine if I run script using below command
‘sudo python /home/pi/lionsfort/hydroponic.py’. To stop the execution I type CTRL+C then script stops properly with relay getting power off.

Since I wanted script to start with Raspberry pi, I am running ‘hydroponic.py’ script as a service. But with script running as service created below problems
1. Only console logs getting written and file logs are empty.
2. Script starts ok with relay functioning properly, but when I stop the service (sudo systemctl stop hydroponic.service) relay wont get power off.
3. Script start with raspberry pi power on but also start with every new PUTTY session. There should be only one instance of script running irrespective PUTTY session.

Note: If run script using ‘sudo python /home/pi/lionsfort/hydroponic.py’ I don’t face any of above problems!!

Followed below process to run script as a service on boot: (ref http://www.diegoacuna.me/how-to-run-a-sc...an-jessie/)
1. cd /lib/systemd/system/
2. sudo nano hydroponic.service
3. hydroponic.service content
[Unit]
Description=Hydroponic
After=multi-user.target

[Service]
Type=simple
ExecStart=/usr/bin/python /home/pi/lionsfort/hydroponic.py
Restart=on-abort

[Install]
WantedBy=multi-user.target

4. To activate it, I ran below commands
a. sudo chmod 644 /lib/systemd/system/ hydroponic.service
b. chmod +x /home/pi/lionsfort/hydroponic.py
c. sudo systemctl daemon-reload
d. sudo systemctl enable hydroponic.service
e. sudo systemctl start hydroponic.service

logging.json

--
Satish Gunjal
Reply
#2
Systemd logs into syslog, try to run:

sudo journalctl -u hydroponic
Also check the /var/log folder, maybe the stdout of your service is writing in the /var/log/message file.

About file logs, use the full path when writing them.
/home/pi/lionsfort/hydroponic.log
Reply
#3
@gontajones Logs issue resolved after giving the full path of the log file. Thanks! Also please help me on issue 2: command " sudo systemctl stop hydroponic.service" stops service but relays are still power on!
Reply
#4
Good, you're welcome!

About the "systemctl stop" command, it sends a SIGTERM to the service.
You'll have to get this signal (try: except:), reset the relays (clear GPIOs) and then exit.

Maybe your code now is just exiting.
Reply
#5
Code snippet as below. Please suggest where to make change?

try:
    initialize()
    while True:	
        hourMinute = datetime.now().strftime('%H:%M')
        logger.info("Main()> hourMinute= " + hourMinute)
	
	humidityAndTemp();
	
        if(iState == 'off'):
            startInletFan(hourMinute)
        else:
            stopInletFan(hourMinute)            
        
	if(eState == 'off'):
            startExhaustFan(hourMinute)
        else:
            stopExhaustFan(hourMinute)
        
	if(vState == 'off'):
            startVentilationFan(hourMinute)
        else:
            stopVentilationFan(hourMinute)

	if(pState == 'off'):
            startPump(hourMinute)
        else:
            stopPump(hourMinute)
	
	time.sleep(30)

# End program cleanly with keyboard
except KeyboardInterrupt:
    print " Quit"

# Reset GPIO settings
GPIO.cleanup()
Reply
#6
Could you edit your post (code) using the python tags?
Just click on "Insert python" at text formatting bar when editing (writing) posts.
Reply
#7
done.
Reply
#8
import time
import signal
import sys

def handler(signum, frame):
    print 'Got SIGTERM!'
    sys.exit(0) # raises a SystemExit exception

# Register a handler (function) for the SIGTERM signal
signal.signal(signal.SIGTERM, handler)

try:
    initialize()
    while True:
        hourMinute = datetime.now().strftime('%H:%M')
        logger.info("Main()> hourMinute= " + hourMinute)

        humidityAndTemp();

        if(iState == 'off'):
            startInletFan(hourMinute)
        else:
            stopInletFan(hourMinute)

        if(eState == 'off'):
            startExhaustFan(hourMinute)
        else:
            stopExhaustFan(hourMinute)

        if(vState == 'off'):
            startVentilationFan(hourMinute)
        else:
            stopVentilationFan(hourMinute)

        if(pState == 'off'):
            startPump(hourMinute)
        else:
            stopPump(hourMinute)

        time.sleep(30)

# End program cleanly with keyboard or sys.exit(0)
except KeyboardInterrupt:
    print " Quit (Ctrl+C)"
except SystemExit:
    print " Quit (SIGTERM)"

# Reset GPIO settings
GPIO.cleanup()
Reply
#9
thanks. all issues resolved!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Is there a *.bat DOS batch script to *.py Python Script converter? pstein 3 3,185 Jun-29-2023, 11:57 AM
Last Post: gologica
Shocked Issues Installing Pyenv/Python 3.9.1 Brandon_Contactum 1 2,517 Feb-22-2022, 06:32 PM
Last Post: snippsat
  Strange problem related to "python service" Pavel_47 1 1,404 Dec-07-2021, 12:52 PM
Last Post: Pavel_47
  How to kill a bash script running as root from a python script? jc_lafleur 4 5,875 Jun-26-2020, 10:50 PM
Last Post: jc_lafleur
  crontab on RHEL7 not calling python script wrapped in shell script benthomson 1 2,290 May-28-2020, 05:27 PM
Last Post: micseydel
  Help for Windows service recycling script Rajesh_K 1 1,817 Apr-22-2020, 06:07 PM
Last Post: Larz60+
  Use Python to start/stop a server service via a webform? oakleaf2001 0 1,748 Apr-04-2020, 06:14 AM
Last Post: oakleaf2001
  Create Service like window service jesssajan 3 2,981 Mar-06-2020, 01:09 PM
Last Post: ibreeden
  Logger file rotation not working when python code started from windows service as exe nirvantosh 1 6,641 Jun-14-2019, 03:58 PM
Last Post: nirvantosh
  Package python script which has different libraries as a single executable or script tej7gandhi 1 2,618 May-11-2019, 08:12 PM
Last Post: keames

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020