Python:将子流程模块从v3.3导入到v2.7.4

我想从py v3.3导入子进程模块到v2.7,以便能够使用超时功能.

看了几篇帖子后我试了这个

from __future__ import subprocess

但它说:

SyntaxError: future feature subprocess is not defined

然后我发现未来没有任何特征子进程.

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

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

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 backport

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
点赞