Reputation: 333
For example, I have a command commandA and want to get the the exit code after commandA is executed. CommandA is expected to be failed, so the exit code we should get is 1.
If I type command in the terminal as commandA;echo $?
, a 1 get displayed on the screen. However, when I do it with python, things went wrong.
I have tried to call commandA with os.system(commandA)
or subprocess.call(commandA.split())
, and then call os.popen('echo $?').read()
, results are 0.
os.popen('commandA;echo $?').read()
gives me a correct result but the process of commandA is not displayed in the screen, which is what I don't want it happens.
Upvotes: 4
Views: 9507
Reputation: 7081
It kind of depends on python version. You can do:
result=subprocess.check_output(['commandA'],Shell='True')
For 3.x you do:
result = subprocess.run(['ls', '-l'], stdout=subprocess.PIPE)
Or you can do with a try catch to see only errors. Something like:
try:
output = subprocess.check_output(["command"])
except subprocess.CalledProcessError as e:
errorCode = e.returncode
Upvotes: 2
Reputation: 182000
subprocess.call
returns the exit code directly:
exit_code = subprocess.call(commandA.split())
The reason your attempts with echo $?
are not working is that both echo
(typically) and $?
(certainly) are constructs of the shell, and don't exist in Python.
Upvotes: 10