Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get exit code of a command

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.

like image 552
Jieke Wei Avatar asked Oct 24 '25 10:10

Jieke Wei


2 Answers

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.

like image 139
Thomas Avatar answered Oct 26 '25 00:10

Thomas


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
like image 29
Veselin Davidov Avatar answered Oct 25 '25 22:10

Veselin Davidov