Python as Windows Service

This is the place for queries that don't fit in any of the other categories.

Python as Windows Service

Postby Crimson King » Fri Mar 08, 2013 3:14 pm

Hello everyone, first post here in the forums. I'll post the code and then explain a bit (it's pretty short and not complicated at all)

Code: Select all

MAX_ERROR = 29

while(1):
         cont = 0
         ping = subprocess.Popen(
            ["ping", "-n", "40","xxx.xxx.xx.x"],
            stdout = subprocess.PIPE,
            stderr = subprocess.PIPE
         )
         out, error = ping.communicate()
         cant1 = re.findall('Host de destino inaccesible',out)  #These strings mean the host is unreachable or time out (my computer's language is set to spanish)
         cant2 = re.findall('Tiempo de espera agotado',out)   #
         cont = len(cant1) + len(cant2)                         
         if cont > MAX_ERROR:
                                break


This code pings a certain ip 40 times, if you get more than 29 time outs or host unreachable messages the program stops.

Now the tricky part, i need to run this as a windows service. But can't make it work as intended:

Code: Select all
import win32serviceutil
import win32service
import win32event

class SmallestPythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "SmallestPythonService"
    _svc_display_name_ = "display service"

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

if __name__=='__main__':
    win32serviceutil.HandleCommandLine(SmallestPythonService)


I can install, run and stop the service from the command line, but can't figure out how to stop the service when my condition's met.

There's probably a more Pythonic way to do this, any suggestions will be much appreciated.

Cheers.
User avatar
Crimson King
 
Posts: 85
Joined: Fri Mar 08, 2013 2:42 pm
Location: Buenos Aires, Argentina

Re: Python as Windows Service

Postby pydsigner » Sat Mar 09, 2013 12:27 am

I'm assuming that the answer might lie in the source or help of win32serviceutil. But I don't have Windows, so I can't help you more than that. :?
Desktop: Linux Mint 16, 8GB RAM, 500GB HDD, 2.4GHz Xeon
Laptop: Win8.1, 8GB RAM, 1TB HDD, 1.6GHz 4th gen i5
Python: 2.7.4

For God sent not His Son into the world to condemn the world, but that the world through Him might be saved! (John 3:17)
pydsigner
 
Posts: 20
Joined: Sat Feb 23, 2013 12:17 am
Location: Midwestern United States


Return to General Coding Help

Who is online

Users browsing this forum: Baidu [Spider], Google [Bot] and 3 guests