Killing a Windows service programmatically in python

Viewed 174

I would like to rapidly kill a windows service, rather than stopping it. The service is a python process, so the name of the process is python.exe, and thus I cannot kill the process by name. At the moment, I am using sc queryex servicename, then parsing the PID from that and killing by PID. This is problematic for my subprocessing (I am currently shutting down many services at once using Popen and contextlib.exitstack), as this would require two commands to be run, and thus only one of those commands can be parallelized.

Is it possible to do this in one go? Here is my code:

# This portion is not parallel
pid_data = subprocess.check_output(["sc", "queryex", "svcname"])

if pid_data[0] != "PID":
    raise ValueError("Incorrect line number while running svc search.")
else:
    msgsvc_pid = int(pid_data[1])

with contextlib.ExitStack() as stack:
    # This portion is parallel
    stack.enter_context(self._kill_service_by_pid(msgsvc_pid, quiet))
    for svc in svc_list:
        stack.enter_context(self._kill_service(svc, quiet))

Where _kill_service_by_pid and _kill_service are both methods that call taskkill to kill a service, either by process name or PID.

0 Answers
Related