5

我想将subprocess模块从 py v3.3 导入到 v2.7 以便能够使用该timeout功能。

在阅读了几篇文章后,我尝试了这个

from __future__ import subprocess

但它说:

SyntaxError: future feature subprocess is not defined

然后我发现future没有任何功能subprocess

那么我应该在哪里以及如何subprocess从 v3.3 导入?

4

1 回答 1

3

我认为反向移植是个好主意。这里是一个比较subprocess.call。请注意,在 Python2 中具有命名参数timeout*popenargs语法错误,因此向后移植有一个解决方法。其他函数的超时参数处理方式类似。如果您对超时的实际实现方式感兴趣,您应该查看wait方法。Popen

Python2.7子进程

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

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

    retcode = call(["ls", "-l"])
    """
    return Popen(*popenargs, **kwargs).wait()

Python3.3子进程

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:
            p.kill()
            p.wait()
            raise

Python2.7 subprocess32 反向移植

def call(*popenargs, **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"])
    """
    timeout = kwargs.pop('timeout', None)
    p = Popen(*popenargs, **kwargs)
    try:
        return p.wait(timeout=timeout)
    except TimeoutExpired:
        p.kill()
        p.wait()
        raise
于 2013-08-22T06:00:17.497 回答