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


         cont = 0
         ping = subprocess.Popen(
            ["ping", "-n", "40",""],
            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:

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

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

if __name__=='__main__':

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.

User avatar
Crimson King
Posts: 166
Joined: Fri Mar 08, 2013 2:42 pm
Location: Dublin, Ireland

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. :?
Laptop: Manjaro Linux, 32GB RAM, 512GB SSD, i7-6820HQ
Python: 2.7.12

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)
User avatar
Posts: 34
Joined: Sat Feb 23, 2013 12:17 am
Location: Midwestern United States

Return to General Coding Help

Who is online

Users browsing this forum: Google [Bot], Yahoo [Bot] and 6 guests