从python异常中终止Bash脚本

2024-09-28 01:34:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为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"

如果我执行此操作,下面的行仍会打印出来。在

^{pr2}$

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

有没有一种方法可以在上面的except块中创建并杀死一个subprocess,它会杀死整个shell脚本吗?在

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

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


Tags: ofimportecho脚本bashbinsysexception
3条回答

终止整个脚本的一种方法是保存PID,然后在异常发生时使用Python的系统命令在PID上执行kill命令。如果我们导入“操作系统”,它将大致如下:

# In a shell
PID=$$
...
// Some Python Exception happens
os.system('kill -9' + $PID)

在shell脚本中,有两个选项:

  • set -e:所有错误都退出脚本
  • 检查python子命令返回代码,如果非零则中止

(这里可能有更多细节:Aborting a shell script if any command returns a non-zero value?

现在,如果不想更改shell脚本的处理方式,可以获取python脚本的父进程并将其杀死:

except Exception as e:
    import os,signal,sys
    print("Exception: %s" % e)
    os.kill(os.getppid(),signal.SIGTERM)
    sys.exit(2)

如果您在windows上需要此功能,但这不起作用(os.kill不存在),您必须调整它以调用taskkill

^{pr2}$

现在我要说,终止父进程是不好的做法。除非您不控制这个父进程的代码,否则您应该尝试优雅地处理退出。在

整个EOF ... EOF块在Python运行时中执行,因此退出它不会影响bash脚本。如果您想停止进一步的bash脚本进程,那么需要收集exit状态并在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"

相关问题 更多 >

    热门问题