Getting an error - the AttributeError object: 'module' does not have the 'run' attribute when running subprocess.run (["ls", "-l"])

I am running on AIX 6.1 and using Python 2.7. Do you want to execute the next line, but get an error message.

subprocess.run(["ls", "-l"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'run'
+4
source share
1 answer

The function exists only in Python 3.5 and later. subprocess.run()

However, backport is easy enough:

def run(*popenargs, input=None, check=False, **kwargs):
    if input is not None:
        if 'stdin' in kwargs:
            raise ValueError('stdin and input arguments may not both be used.')
        kwargs['stdin'] = subprocess.PIPE

    process = subprocess.Popen(*popenargs, **kwargs):
    try:
        stdout, stderr = process.communicate(input)
    except:
        process.kill()
        process.wait()
        raise
    retcode = process.poll()
    if check and retcode:
        raise subprocess.CalledProcessError(
            retcode, process.args, output=stdout, stderr=stderr)
    return retcode, stdout, stderr

There is no timeout support and no custom class for complete process information, so I only return data retcode, stdoutand stderr. Otherwise, it does the same as the original.

+9

Source: https://habr.com/ru/post/1660692/


All Articles