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

标签 python python-2.7 python-3.x future

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

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

from __future__ import subprocess

但是它说:

SyntaxError: future feature subprocess is not defined

然后我发现 future 没有任何特性 subprocess

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

最佳答案

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

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

关于Python:将子流程模块从 v3.3 导入到 v2.7.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18372395/

相关文章:

python - 在 python 中迭代一个漂亮的 soup 数组

python - 按组重新索引 Pandas 时间序列

python - PIP 无法升级 setuptools

python-2.7 - 如何对 pandas 中的某些行索引重新排序

python : split a list dynamically

python - Iteritems 返回格式化的字符串

python - Python中嵌套不规则列表(不同子列表长度和对象类型)的整数最大值

python-3.x - 用于 Python 3.6 的 cx_Oracle

python - H2O 时的 MAPE 公制

python - 在 Python 中的日期范围内为每年创建新行?