Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Importing subprocess modules from v3.3 to v2.7.4

I want to import subprocess module from py v3.3 to v2.7 to be able to use the timeout functionality.

After reading few posts I tried this

from __future__ import subprocess

But it says:

SyntaxError: future feature subprocess is not defined

Then I found out that future doesn't have any feature subprocess.

So where and how should I import the subprocess from v3.3?

like image 300
Abhiraj Darshankar Avatar asked Oct 21 '22 02:10

Abhiraj Darshankar


1 Answers

I think the backport is a good idea. Here is a comparison of subprocess.call. Note that having the named parameter timeout after *popenargs is a syntax error in Python2, so the backport has a workaround. The timeout parameter for the other functions is handled similarly. You should look at the wait method of Popen if you are interested in how the timeout is actually implemented.

Python2.7 subprocess

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 subprocess

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
like image 178
John La Rooy Avatar answered Nov 03 '22 07:11

John La Rooy