【发布时间】:2017-07-22 12:53:14
【问题描述】:
使用 Windows 服务控制台,您可以在属性 > 依赖项下查看服务依赖项。如何使用 Python 获得相同的信息?有没有办法用 psutil 做到这一点?
【问题讨论】:
标签: python windows service dependencies psutil
使用 Windows 服务控制台,您可以在属性 > 依赖项下查看服务依赖项。如何使用 Python 获得相同的信息?有没有办法用 psutil 做到这一点?
【问题讨论】:
标签: python windows service dependencies psutil
您可以使用subprocess 模块查询sc.exe 以获取您的服务的信息,然后解析出依赖关系信息。比如:
import subprocess
def get_service_dependencies(service):
try:
dependencies = [] # hold our dependency list
info = subprocess.check_output(["sc", "qc", service], universal_newlines=True)
dep_index = info.find("DEPENDENCIES") # find the DEPENDENCIES entry
if dep_index != -1: # make sure we have a dependencies entry
for line in info[dep_index+12:].split("\n"): # loop over the remaining lines
entry, value = line.rsplit(":", 2) # split each line to entry : value
if entry.strip(): # next entry encountered, no more dependencies
break # nothing more to do...
value = value.strip() # remove the whitespace
if value: # if there is a value...
dependencies.append(value) # add it to the dependencies list
return dependencies or None # return None if there are no dependencies
except subprocess.CalledProcessError: # sc couldn't query this service
raise ValueError("No such service ({})".format(service))
然后您可以轻松地查询依赖项:
print(get_service_dependencies("wudfsvc")) # query Windows Driver Foundation service
# ['PlugPlay', 'WudfPf']
【讨论】: