Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting an error - AttributeError: 'module' object has no attribute 'run' while running subprocess.run(["ls", "-l"])

I am running on a AIX 6.1 and using Python 2.7. Want to execute following line but getting an error.

subprocess.run(["ls", "-l"])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'run'
like image 630
nisarga lolage Avatar asked Nov 14 '16 13:11

nisarga lolage


People also ask

How do you call a subprocess in Python?

To start a new process, or in other words, a new subprocess in Python, you need to use the Popen function call. It is possible to pass two parameters in the function call. The first parameter is the program you want to start, and the second is the file argument.

What is popen in subprocess?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.

How do you check subprocess output?

The subprocess. check_output() is used to get the output of the calling program in python. It has 5 arguments; args, stdin, stderr, shell, universal_newlines. The args argument holds the commands that are to be passed as a string.

How do I get stdout of subprocess run?

To capture the output of the subprocess. run method, use an additional argument named “capture_output=True”. You can individually access stdout and stderr values by using “output. stdout” and “output.


1 Answers

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

It is easy enough to backport however:

def run(*popenargs, **kwargs):     input = kwargs.pop("input", None)     check = kwargs.pop("handle", False)      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 support for timeouts, and no custom class for completed process info, so I'm only returning the retcode, stdout and stderr information. Otherwise it does the same thing as the original.

like image 50
Martijn Pieters Avatar answered Oct 03 '22 00:10

Martijn Pieters