我有以下在 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 脚本应该用陷阱清除构建锁。当发生任何其他运行时错误时,我也会处理并打印它以获取上下文和信息。
当然还有其他异常类型我没有明确处理,但那些目前不会导致陷阱被执行。
感谢帮助!!
最佳答案
当 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
关于python - python 错误退出后未执行 Bash 陷阱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24482147/