python - 我们如何杀死 python 中 subprocess.call() 函数产生的进程?

标签 python python-2.7

我在 python 中用 subprocess.call 创建了一个进程

import subprocess
x = subprocess.call(myProcess,shell=True)

我想杀死这两个进程,即 shell 及其子进程(我的进程)。

使用 subprocess.call() 我只得到进程的返回码

有人能帮忙吗 ?

最佳答案

你必须离开 subprocess.call这样做,但它仍然会达到相同的结果。子进程调用运行传递的命令,等待完成然后返回返回码属性。在我的示例中,我展示了如何在需要时在完成时获取返回码。

这是如何终止子进程的示例,您必须拦截 SIGINT (Ctrl+c) 信号才能在退出主进程之前终止子进程。如果需要,还可以从子流程中获取标准输出、标准错误和返回码属性。

#!/usr/bin/env python
import signal
import sys
import subprocess

def signal_handler(sig, frame):
    p.terminate()
    p.wait()
    sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)

p = subprocess.Popen('./stdout_stderr', shell=True, 
    stderr=subprocess.PIPE, stdout=subprocess.PIPE)
# capture stdout and stderr
out, err = p.communicate()
# print the stdout, stderr, and subprocess return code
print(out)
print(err)
print(p.returncode)

关于python - 我们如何杀死 python 中 subprocess.call() 函数产生的进程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60996474/

相关文章:

python - 使用 Beautifulsoup Python 从 URL 抓取数据时获取编码文本

Python - 为什么导入子模块会使包可见?

Python编程-从Excel工作表中查找无效记录

Python 作用域为 : I copied a list object in a function and modified the duplicate, 但原始内容已更改。为什么?

python - 实现一个完整的 Python Unix 风格的守护进程

python - python2 和 python3 中的字典的 __repr__()

python - Pandas 的时间事件研究

python - 按多维数组中的值(前 5 个)排序

python - 在单元测试中使用 Flask 作为回调端点?

python - 使用 10**9 的成本超过 1000000000?