如何在python中的shell脚本中设置退出状态

use*_*237 7 python unix shell

我想获得在从python调用的shell脚本中设置的退出状态.代码如下

python脚本.

result = os.system("./compile_cmd.sh")
print result
Run Code Online (Sandbox Code Playgroud)

(compile_cmd.sh)

javac @source.txt
#i do some code here to get the no of compilation errors
if [$error1 -e 0 ]
then
echo "\n********** JAVA compilation sucessfull **********"
exit 0
else
echo "\n** JAVA Compilation Error in file ** File not checked in to CVS **"
exit 1
fi
Run Code Online (Sandbox Code Playgroud)

我正在运行此代码.但无论我返回什么退出状态,我得到的结果var为0(我认为它返回shell脚本是否成功运行)我知道如何获取我在shell脚本中设置的退出状态python脚本??

cpt*_*tPH 11

import subprocess
result = subprocess.Popen("./compile_cmd.sh")
text = result.communicate()[0]
returncode = result.returncode
Run Code Online (Sandbox Code Playgroud)

从这里开始:使用Python子进程通信方法时如何获取退出代码?


mkl*_*nt0 10

要使用推荐的Python v3.5+方法补充cptPH 的有用答案,请使用:subprocess.run()

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 = subprocess.run('./compile_cmd.sh')

# Print the exit code.
print(completedProc.returncode)
Run Code Online (Sandbox Code Playgroud)