xyz*_*xyz 10 python subprocess python-2.5
我想使用Python 2.6的子进程版本,因为它允许Popen.terminate()函数,但我坚持使用Python 2.5.在我的2.5代码中使用较新版本的模块是否有一些相当干净的方法?某种from __future__ import subprocess_module?
我知道这个问题已经得到了解答,但是对于它的价值,我已经subprocess.py在Python 2.3中使用了Python 2.6并且它运行良好.如果你阅读文件顶部的评论,它说:
# This module should remain compatible with Python 2.2, see PEP 291.
实际上并没有很好的方法.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代码而不是整个模块.