Windows does not maintain a process tree, so killing child processes will not always work if the process structure has been broken, e.g. because a process only acts as a "launcher" and then terminates itself.
Specifically it will not work for Windows Terminal since wt.exe
will launch WindowsTerminal.exe
and then terminate itself. WindowsTerminal.exe
launches wsl.exe
and conhost.exe
which are both terminated. Finally there will be 3 processes left: OpenConsole.exe
, powershell.exe
and WindowsTerminal.exe
.
That said, psutil.Process.children to the rescue:
import psutil
import subprocess
process = subprocess.Popen(["wt", "-w 001"])
children = psutil.Process(process.pid).children(recursive=True)
for child in children:
child.terminate() # friendly termination
_, still_alive = psutil.wait_procs(children, timeout=3)
for child in still_alive:
child.kill() # unfriendly termination