检查Python是否存在Windows服务

ECC*_*ECC 2 python windows-services

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

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

win32serviceutil.QueryServiceStatus('myservice')
Run Code Online (Sandbox Code Playgroud)

这是错误:

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')
Run Code Online (Sandbox Code Playgroud)

有什么方法可以检查吗?

Pro*_*ver 6

它可以使用psutil:

这是代码:

from __future__ import print_function
import psutil

def get_service(name):
    service = None
    try:
        service = psutil.win_service_get(name)
        service = service.as_dict()
    except Exception as ex:
        # raise psutil.NoSuchProcess if no service with such name exists
        print(str(ex))

    return service

service = get_service('LanmanServer')

if service:
    print("Service found: ", service)
else:
    print("Service not found")

if service and service['status'] == 'running':
    print("Service is running")
else: 
    print("Service is not running")
Run Code Online (Sandbox Code Playgroud)


小智 5

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

try: 
    win32serviceutil.QueryServiceStatus('myservice')
except:
    print "Windows service NOT installed"
else:
    print "Windows service installed"
Run Code Online (Sandbox Code Playgroud)