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

时间:2013-12-03 09:48:31

标签: python shell unix

我希望在从python调用的shell脚本中设置退出状态。 代码如下

python脚本。

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

(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

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

3 个答案:

答案 0 :(得分:10)

import subprocess
result = subprocess.Popen("./compile_cmd.sh")
text = result.communicate()[0]
returncode = result.returncode

从这里采取:How to get exit code when using Python subprocess communicate method?

答案 1 :(得分:1)

使用cptPH's helpful answer通过推荐的 Python v3.5 + 方法补充subprocess.run()

import subprocess

# Invoke the shell script (without 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)

答案 2 :(得分:0)

import subprocess
proc = subprocess.Popen("Main.exe",stdout=subprocess.PIPE,creationflags=subprocess.DETACHED_PROCESS)
result,err = proc.communicate()
exit_code = proc.wait()
print(exit_code)
print(result,err)

在 subprocess.Popen -> 创建标志用于在分离模式下创建进程 如果您不想分离更多,请删除该部分。
subprocess.DETACHED_PROCESS -> 在python进程之外运行进程

使用 proc.communicate() -> 你可以得到他的输出和该过程中的错误 proc.wait() 将等待进程完成并给出程序的退出代码。

<块引用>

注意:subprocess.popen() 和 proc.wait() 之间的任何命令都会在等待调用时照常执行,在子进程完成之前不会进一步执行。