首页 > 解决方案 > 从 python 异常中杀死 Bash 脚本

问题描述

我里面有一个调用 Python 的 shell 脚本。

#! /bin/bash

shopt -s extglob
echo "====test===="
~/.conda/envs/my_env/bin/python <<'EOF'

import sys
import os


try:
    print("inside python")
    x = 2/0
except Exception as e:
    print("Exception: %s" % e)
    sys.exit(2)
print("at the end of python")
EOF
echo "end of script"

如果我执行这个,下面的行仍然会被打印出来。

"end of script"

我想在python脚本的异常块中退出shell,让脚本无法到达EOF

有没有办法subprocess在上面的except块中创建和杀死 a ,这会杀死整个 shell 脚本?

我可以通过杀死整个 shell 脚本来生成一个虚拟子进程并在异常块内杀死它吗?

任何例子都会有所帮助。提前致谢。

标签: pythonbashshellsubprocesssh

解决方案


整个EOF ... EOF块在 Python 运行时中执行,因此退出它不会影响 bash 脚本。如果要停止进一步的 bash 脚本进度,则需要收集退出状态并在 Python 执行后检查它,即:

#!/bin/bash

~/.conda/envs/my_env/bin/python <<'EOF'
import sys

sys.exit(0x01)  # use any exit code from 0-0xFF range, comment out for a clean exit

print("End of the Python script that will not execute without commenting out the above.")
EOF

exit_status=$?  # store the exit status for later use

# now lets check the exit status and see if python returned a non-zero exit status
if [ $exit_status -ne 0 ]; then
    echo "Python exited with a non-zero exit status, abort!"
    exit $exit_status  # exit the bash script with the same status
fi
# continue as usual...
echo "All is good, end of script"

推荐阅读