我有以下在Ubuntu 12上运行的bash脚本:
#!/bin/bash -e
if [[ -f ".build.lock" ]]; then
echo "A build is already in progress by another user. Unable to continue, exiting."
echo " If this is a mistake, delete the '.build.lock' file to forcefully unlock"
exit 1
else
touch .build.lock
echo "Build Lock Created"
pushd ~/build-server-scripts > /dev/null
# Execute main build script
python3 my-build.py "$@"
popd > /dev/null
fi
__cleanup()
{
echo "Build Lock Removed"
[[ -f ".build.lock" ]] && rm ".build.lock"
}
trap __cleanup EXIT
每当我从我的python脚本中抛出一个异常(大多数都是未处理的)时,我希望bash脚本随后也会失败并执行TRAP。但事实并非如此。我在这里缺少什么?
以下是我在python(使用python 3.2)脚本中处理错误的示例:
try:
# Do lots of other business logic here
# 'os.setsid' needed to terminate process later for interrupts.
process = subprocess.Popen('./ziosk-build.sh', preexec_fn=os.setsid)
process.communicate()
except KeyboardInterrupt:
print('\n\nSIGINT (CTRL+C?) received; stopping\n')
try:
os.killpg(process.pid, signal.SIGTERM)
except NameError:
pass
except RuntimeError as e:
print('>>> ERROR >>>', e)
sys.exit(1)
在上面的脚本中,我明确地处理了一些例外。当我得到键盘中断时,我想退出并调用它的bash脚本应该用陷阱清理构建锁。当发生任何其他运行时错误时,我也会处理并打印它以用于上下文&信息。
当然还有其他我没有明确处理的异常类型,但是那些当前没有导致陷阱被执行。
帮助表示赞赏!!
答案 0 :(得分:2)
当Python脚本出错时,不会执行__cleanup
函数,因为脚本在到达注册处理程序的trap __cleanup EXIT
语句之前退出。将trap
语句和__cleanup
函数放在脚本的顶部。
#!/bin/bash -e
__cleanup()
{
echo "Build Lock Removed"
[[ -f ".build.lock" ]] && rm ".build.lock"
}
trap __cleanup EXIT
if [[ -f ".build.lock" ]]; then
echo "A build is already in progress by another user. Unable to continue, exiting."
echo " If this is a mistake, delete the '.build.lock' file to forcefully unlock"
exit 1
else
touch .build.lock
echo "Build Lock Created"
pushd ~/build-server-scripts > /dev/null
# Execute main build script
python3 my-build.py "$@"
popd > /dev/null
fi