[python-win32] How to invoke Python program from Windows service?
Tim Golden
mail at timgolden.me.uk
Fri Jun 22 14:17:08 CEST 2012
> Yeah, that was exactly my problem; I had no way to diagnose what was
> going on, and needed a springboard to tell me what I needed to know
> in order to figure out what was happening (or not). I could verify
> that the script *worked*, since I could run it from a DOS prompt
> without errors. But when I ran it using CreateProcess (and
> ProcessStartInfo), I didn't see it execute (since it would have
> created a file in its directory).
>
> However, your answer that I can write it directly with pywin32
> intrigues me, especially since I'd rather develop in Python anyway.
> I'll go see what's involved in doing that. Thanks for the pointer!
For reference, this is the kind of pattern I use when writing
Windows Services in Python:
<my_module.py>
class Engine(object):
def __init__(self):
self._stop_event = threading.Event()
def start(self):
# do stuff until self._stop_event is set
def stop(self):
# set self._stop_event
if __name__ == '__main__':
Engine().start()
</my_module.py>
<my_service.py>
import win32event
import win32service
import win32serviceutil
import my_module
class Service (win32serviceutil.ServiceFramework):
_svc_name_ = "MyService"
_svc_display_name_ = "A Service of Mine"
def __init__ (self, args):
win32serviceutil.ServiceFramework.__init__ (self, args)
self.stop_event = win32event.CreateEvent (None, 0, 0, None)
self.engine = my_module.Engine ()
def SvcDoRun (self):
self.engine.start (True)
win32event.WaitForSingleObject (self.stop_event, win32event.INFINITE)
def SvcStop (self):
self.ReportServiceStatus (win32service.SERVICE_STOP_PENDING)
self.engine.stop ()
win32event.SetEvent (self.stop_event)
if __name__ == '__main__':
win32serviceutil.HandleCommandLine (Service)
</code>
To install the service you run the my_service.py module with
the parameter "install". (The reverse is done by passing "remove").
HTH
TJG
More information about the python-win32
mailing list