检查Python是否存在Windows服务

时间:2015-11-21 11:54:03

标签: python windows-services

我在python中编写了一个与Windows服务交互的程序。但是,在执行此操作之前,我需要检查服务是否已安装。

我正在使用以下代码来获取服务。但如果它不存在,我会收到错误。

win32serviceutil.QueryServiceStatus('myservice')

这是错误:

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

有什么方法可以检查吗?

2 个答案:

答案 0 :(得分:6)

可以使用psutil

完成

以下是代码:

import psutil

def getService(name):

        service = None
        try:
            service = psutil.win_service_get(name)
            service = service.as_dict()
        except Exception as ex:
            print str(ex)

        return service

service = getService('LanmanServer')

print service

if service:

        print "service found"
else:

    print "service not found"


if service and service['status'] == 'running' :

        print "service is running"
else :

        print "service is not running"

答案 1 :(得分:5)

似乎Try-Except块是最简单的解决方案:

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