这是我想在Python中模仿的工作C#代码。
var process = Process.Start("wt", "-w 001");
Thread.Sleep(2000);
process.Kill(entireProcessTree: true);我试过了,但没用。
process = subprocess.Popen(["wt", "-w 001"])
time.sleep(2)
process.kill()发布于 2022-01-03 12:28:46
Windows不维护进程树。,因此,如果进程结构被破坏,那么杀死子进程并不总是有效的,例如,因为一个进程只是充当一个“启动程序”,然后终止自己。
具体来说,它将不适用于窗口终端,因为wt.exe将启动WindowsTerminal.exe,然后终止自身。WindowsTerminal.exe启动wsl.exe和conhost.exe,它们都被终止。最后,剩下3个进程:OpenConsole.exe、powershell.exe和WindowsTerminal.exe。
话虽如此,psutil.Process.children来拯救:
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 terminationhttps://stackoverflow.com/questions/70565429
复制相似问题