在Python 2.5中使用Python 2.6子进程模块

xyz*_*xyz 10 python subprocess python-2.5

我想使用Python 2.6的子进程版本,因为它允许Popen.terminate()函数,但我坚持使用Python 2.5.在我的2.5代码中使用较新版本的模块是否有一些相当干净的方法?某种from __future__ import subprocess_module

Kam*_*iel 9

我知道这个问题已经得到了解答,但是对于它的价值,我已经subprocess.py在Python 2.3中使用了Python 2.6并且它运行良好.如果你阅读文件顶部的评论,它说:

# This module should remain compatible with Python 2.2, see PEP 291.

  • PEP 291对于了解非常有用.谢谢!(链接,为了其他人的方便:http://www.python.org/dev/peps/pep-0291/)我已经确定你的回答更准确地回答了我的问题,即使zacherates'也非常有帮助. (2认同)
  • 警告:这不是真的.2.6子进程模块中的close_fds参数实现使用os.closerange(),它是python 2.6中的新增功能 (2认同)

Aar*_*paa 6

实际上并没有很好的方法.subprocess是在python实现的(而不是C),所以你可以想象在某处复制模块并使用它(当然希望它不使用任何2.6优点).

另一方面,您可以简单地实现子进程声明要执行的操作,并编写一个在*nix上发送SIGTERM并在Windows上调用TerminateProcess的函数.以下实现已经在Linux和Win XP vm上测试过,你需要python Windows扩展:

import sys

def terminate(process):
    """
    Kills a process, useful on 2.5 where subprocess.Popens don't have a 
    terminate method.


    Used here because we're stuck on 2.5 and don't have Popen.terminate 
    goodness.
    """

    def terminate_win(process):
        import win32process
        return win32process.TerminateProcess(process._handle, -1)

    def terminate_nix(process):
        import os
        import signal
        return os.kill(process.pid, signal.SIGTERM)

    terminate_default = terminate_nix

    handlers = {
        "win32": terminate_win, 
        "linux2": terminate_nix
    }

    return handlers.get(sys.platform, terminate_default)(process)
Run Code Online (Sandbox Code Playgroud)

这样你只需要维护terminate代码而不是整个模块.