0

This is the working C# code I would like to mimic in Python.

var process = Process.Start("wt", "-w 001");
Thread.Sleep(2000);
process.Kill(entireProcessTree: true);

I tried this but it doesn't work.

process = subprocess.Popen(["wt", "-w 001"])
time.sleep(2)
process.kill()
0lan
  • 179
  • 1
  • 14

1 Answers1

1

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
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
  • Unfortunately it does not work with wt (Windows Terminal), maybe because it is not a win32 application? – 0lan Jan 03 '22 at 12:46
  • @0lan: no, because `wt` is a launcher app for `WindowsTerminal` and then terminates itself, which breaks the process tree. – Thomas Weller Jan 03 '22 at 13:24