Search code examples
pythonpython-3.xsubprocesspywin32

How to interact with 'Windows service' synchronously in python


How about using pywin32 module ? Or is there any way to achieve this through subprocess module ?


Solution

  • I can't imagine how this is possible.

    Windows services do not expose generic messaging API; each service (should it choose to) exposes its own specific API via its own choice of IPC channel (eg. WCF).

    Regardless though, nothing would allow you to do this synchronously; any kind of IPC will be an async call to the service endpoint.

    You kind of need to be more specific in your question.

    The available generic APIs for interacting with a windows service are basically limited to; stop, start, install, uninstall. Have a look here: https://msdn.microsoft.com/en-us/library/windows/desktop/ms685942(v=vs.85).aspx

    (If you are writing a new windows service, in python, ZeroMQ would be a very reasonable choice to interact with it from a command line python script; there are any number of alternative IPC channels for python which would be equally good)

    --

    To just start a service, try:

    import win32service
    import win32serviceutil
    import time
    
    win32serviceutil.StartService(serviceName)
    status = win32serviceutil.QueryServiceStatus(serviceName)
    while status == win32service.SERVICE_START_PENDING:
      time.sleep(1)
      status = win32serviceutil.QueryServiceStatus(serviceName)
    

    Nb. You'll get an access denied error unless you spawn the python instance as administrator.