我有一个名为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脚本在异常块中终止它吗?在
任何例子都会有帮助。 提前谢谢。在
终止整个脚本的一种方法是保存PID,然后在异常发生时使用Python的系统命令在PID上执行kill命令。如果我们导入“操作系统”,它将大致如下:
在shell脚本中,有两个选项:
set -e
:所有错误都退出脚本(这里可能有更多细节:Aborting a shell script if any command returns a non-zero value?)
现在,如果不想更改shell脚本的处理方式,可以获取python脚本的父进程并将其杀死:
如果您在windows上需要此功能,但这不起作用(
^{pr2}$os.kill
不存在),您必须调整它以调用taskkill
:现在我要说,终止父进程是不好的做法。除非您不控制这个父进程的代码,否则您应该尝试优雅地处理退出。在
整个
EOF ... EOF
块在Python运行时中执行,因此退出它不会影响bash脚本。如果您想停止进一步的bash脚本进程,那么需要收集exit状态并在Python执行之后检查它,例如:相关问题 更多 >
编程相关推荐