Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

subprocess checkoutput error

I am trying to check the usage of check_output using he below script and running into compilation error,where am I going wrong?

import os
import subprocess
from subprocess import check_output

#result = subprocess.check_output(['your_program.exe', 'arg1', 'arg2'])
SCRIPT_ROOT=subprocess.check_output(["pwd","shell=True"])
print SCRIPT_ROOT

def main ():
    pass

if __name__ == '__main__':
    main()

Traceback (most recent call last):
  File "test.py", line 3, in <module>
    from subprocess import check_output
ImportError: cannot import name check_output
like image 350
user1927396 Avatar asked Dec 28 '12 00:12

user1927396


People also ask

What is subprocess Check_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.

What is the return type of subprocess Check_output?

CalledProcessError Exception raised when a process run by check_call() or check_output() returns a non-zero exit status. returncode Exit status of the child process.

Does subprocess call raise exception?

The Python subprocess call() function returns the executed code of the program. If there is no program output, the function will return the code that it executed successfully. It may also raise a CalledProcessError exception.


1 Answers

check_output has been introduced in Python 2.7. If you're using an earlier version of python, it's just not there.

Alternative is to use Popen.

output = subprocess.Popen(['pwd'], stdout=subprocess.PIPE).communicate()[0]

Proof of this can be found here.

New function: the subprocess module’s check_output() runs a command with a specified set of arguments and returns the command’s output as a string when the command runs without error, or raises a CalledProcessError exception otherwise.

Demo of the substitute.

import subprocess
cmd = subprocess.Popen(['pwd'], stdout=subprocess.PIPE)
output = cmd.communicate()[0]
print cmd.returncode
print output

Output

> python p.py
/Users/vlazarenko/tests

The only real difference is that Popen won't throw an exception when command returns a non-zero code.

like image 155
favoretti Avatar answered Sep 28 '22 12:09

favoretti