python - python 错误退出后未执行 Bash 陷阱

标签 python linux bash ubuntu python-3.x

我有以下在 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/

相关文章:

linux - Bash 脚本导出文件名到变量

Linux X session 脚本

linux - 如何从文件中以特定单词开头的 bash 输出中保存文本?

bash - 确定连接是有线还是无线?

python - 获取networkx中匹配节点的列表

c# - 具有返回值和输出参数的 Python NET 调用 C# 方法

java - 如何通过过滤掉给定的键集来减少一对 RDD?

python - Django读取JSON文件

linux - Linux服务器上崩溃后如何自动重新启动elasticsearch搜索?

macos - 在 OSX Mavericks 中找不到 mvn 命令