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
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With