如何在Python中终止由子进程创建的进程?

5

在Linux Ubuntu操作系统中,我通过以下方式运行包含GObject循环的test.py脚本:subprocess

subprocess.call(["test.py"])

现在,这个 test.py 将创建进程。有没有一种方法可以在Python中杀死这个进程? 注意:我不知道进程ID。
如果我没有很清楚地解释我的问题,我很抱歉,因为我对这些表格和Python总体上都很陌生。

这段代码能正常工作吗?p = subprocess.call(["test.py"]);p.kill() - Srinivas Reddy Thatiparthy
现在它给我返回:AttributeError: int对象没有kill属性 - Mero
这是一个相关(更复杂)的案例:如何在Python中停止读取进程输出而不挂起? - jfs
3个回答

3

1

subprocess.call() 只是 subprocess.Popen().wait() 的简写形式:

from subprocess import Popen
from threading import Timer

p = Popen(["command", "arg1"])
print(p.pid) # you can save pid to a file to use it outside Python

# do something else..

# now ask the command to exit
p.terminate()
terminator = Timer(5, p.kill) # give it 5 seconds to exit; then kill it
terminator.start()
p.wait()
terminator.cancel() # the child process exited, cancel the hit

0

subprocess.call 等待进程完成并返回退出码(整数)值,因此无法知道子进程的进程 ID。您应该考虑使用 subprocess.Popen,它会 fork() 子进程。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接