【问题标题】:How to kill a process been created by subprocess in python?如何杀死由python中的子进程创建的进程?
【发布时间】:2013-12-18 09:44:48
【问题描述】:

在 Linux Ubuntu 操作系统下,我运行 test.py 脚本,其中包含一个 GObject 循环,使用 subprocess by:

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

现在,这个test.py 将创建进程。有没有办法在 Python 中杀死这个进程? 注意:我不知道进程 ID。

很抱歉,如果我没有很清楚地解释我的问题,因为我是这种表单的新手,而且一般来说是 python 的新手。

【问题讨论】:

标签: python linux python-2.7 subprocess


【解决方案1】:

我建议不要使用subprocess.call,而是构造一个Popen 对象并使用它的API:http://docs.python.org/2/library/subprocess.html#popen-objects

特别是: http://docs.python.org/2/library/subprocess.html#subprocess.Popen.terminate

HTH!

【讨论】:

    【解决方案2】:

    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
    

    【讨论】:

      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-12-05
        • 1970-01-01
        • 2010-12-08
        • 2013-10-27
        • 1970-01-01
        • 2019-06-20
        • 2012-09-02
        • 2011-09-26
        相关资源
        最近更新 更多