【问题标题】:How do we kill the process spawned by subprocess.call() function in python?我们如何杀死 python 中 subprocess.call() 函数产生的进程?
【发布时间】:2020-07-14 17:07:05
【问题描述】:

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

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

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

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

有人可以帮忙吗?

【问题讨论】:

标签: python python-2.7


【解决方案1】:

您想使用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

【讨论】:

    【解决方案2】:

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

    这是一个如何终止子进程的示例,您必须拦截 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)
    

    【讨论】:

    • 您可以使用sleep 3 进行测试
    • @AlexB 好点,我只是把我用来测试这个的代码放在一个要点git.io/JfUuB
    【解决方案3】:

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

    this question 回答了如何杀死使用subprocess.Popen 创建的子进程。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-10
      • 1970-01-01
      • 2016-11-16
      • 1970-01-01
      • 2010-12-08
      相关资源
      最近更新 更多