How to get the exit status set in a shell script in Python


I want to get the exit status set in a shell script which has been called from Python.

The code is as below

Python script

result = os.system("./")
print result


javac @source.txt
# I do some code here to get the number of compilation errors
if [$error1 -e 0 ]
echo "n********** Java compilation successful **********"
exit 0
echo "n** Java compilation error in file ** File not checked in to CVS **"
exit 1

I am running this code, but no matter the what exit status I am returning, I am getting result var as 0 (I think it’s returning whether the shell script ran successfully or not).

How can I fetch the exit status that I am setting in the shell script in the Python script?

Asked By: user2831237



import subprocess

result = subprocess.Popen("./")
text = result.communicate()[0]
return_code = result.returncode

Taken from here: How to get exit code when using Python subprocess communicate method?

Answered By: cptPH

To complement cptPH’s helpful answer with the recommended Python v3.5+ approach using

import subprocess

# Invoke the shell script (without up-front shell involvement)
# and pass its output streams through.
# run()'s return value is an object with information about the completed process. 
completedProc ='./')

# Print the exit code.
Answered By: mklement0
import subprocess
proc = subprocess.Popen("Main.exe",stdout=subprocess.PIPE,creationflags=subprocess.DETACHED_PROCESS)
result,err = proc.communicate()
exit_code = proc.wait()

In subprocess.Popen -> creation flag is used for creating the process in detached mode
if you don’t wnat in detached more just remove that part.
subprocess.DETACHED_PROCESS -> run the process outside of the python process

with proc.communicate() -> you can get he output and the errors from that process
proc.wait() will wait for the process to finish and gives the exit code of the program.

Note: any commands between subprocess.popen() and proc.wait() will execute as usual at the wait call it will not execute further before the subprocess is finished.

Answered By: Rajat Tyagi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.