ECC ECC - 5 months ago 48
Python Question

Check if a Windows Service exists with Python

I wrote a program in python that interacts with a Windows service. However, before doing it, I need check if the service is installed.

I'm using the following code to get the service. But if it not exists, I receive error.

win32serviceutil.QueryServiceStatus('myservice')


This is the error:

Traceback (most recent call last):
File "win32serviceutil.pyc", line 835, in SvcRun
File "main.py", line 54, in SvcDoRun
File "main.py", line 103, in main
File "main.py", line 57, in start_service
File "main.pyc", line 495, in QueryServiceStatus
File "main.pyc", line 80, in SmartOpenService
error: (1060, 'GetServiceKeyName', 'The specified service does not exist as an installed service')


Is there any way I can check it?

Answer Source

It seems like a Try-Except block would be the easiest solution:

try: 
    win32serviceutil.QueryServiceStatus('myservice')
except:
    print "Windows service NOT installed"
else:
    print "Windows service installed"