用Popen打开一个进程并在一段时间后杀死

Vla*_*ZzZ 1 python windows subprocess

我想在5分钟之后杀死一个进程(ex),我打开了

subprocess.Popen()
p = subprocess.Popen('calc.exe', shell=True)  # example
Run Code Online (Sandbox Code Playgroud)

我打印了点子print(p.pid),睡了10秒钟time.sleep(10),然后杀了这个过程p.kill().

问题是calc.exe仍然在运行.我已经用它Process Explorer来看看这里发生了什么,似乎子进程将创建一个带有pid =的cmd,p.pid它会创建calc.exe,但是另一个pid我不知道.

这里的所有代码:

import subprocess, os, time

p = subprocess.Popen('calc.exe', shell=True)

time.sleep(1)
print(p.pid)
p.kill()
Run Code Online (Sandbox Code Playgroud)

那么我做错了什么?

谢谢!

gli*_*dud 6

p.kill()cmd.exe正在通过shell=True选项来杀死你正在产生的进程Popen.这个过程就是p.pid指的.shell=True从你的Popen陈述中删除,它会calc.exe像你期望的那样杀死.