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

2024-04-19 03:09:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我用python创建了一个带有subprocess.call的进程

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

我想杀死两个进程,即shell和它的子进程(我的进程)

对于subprocess.call(),我只获取进程的返回代码

有人能帮忙吗


Tags: 代码importtrue进程shellcallsubprocessmyprocess
3条回答

当使用subprocess.call时,您不能这样做,因为它在运行子进程时会中断您的程序

如何终止使用subprocess.Popen创建的子进程在this question中给出了答案

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

下面是一个如何终止子进程的示例,您必须截获SIGINT(Ctrl+c)信号,以便在退出主进程之前终止子进程。如果需要,还可以从子流程获取标准输出、标准错误和returncode属性

#!/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)

您想使用Popen。下面是subprocess.call的样子:

def call(*popenargs, timeout=None, **kwargs):
"""Run command with arguments.  Wait for command to complete or
timeout, then return the returncode attribute.

The arguments are the same as for the Popen constructor.  Example:

retcode = call(["ls", "-l"])
"""
with Popen(*popenargs, **kwargs) as p:
    try:
        return p.wait(timeout=timeout)
    except:  # Including KeyboardInterrupt, wait handled that.
        p.kill()
        # We don't call p.wait() again as p.__exit__ does that for us.
        raise

subprocess.call专门用于在返回之前等待进程完成。所以,当subprocess.call结束时,没有什么可杀的了

如果您想启动一个子流程,然后在它运行时执行其他操作,包括终止该流程,那么应该直接使用subprocess.Popen

相关问题 更多 >