python - 从 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 脚本来生成一个虚拟子进程并在异常块内杀死它吗?
任何例子都会有所帮助。提前致谢。
解决方案
整个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"
推荐阅读
- vuetify.js - 如何在 v-data-table 中使用 vue2-perfect-scrollbar 使一个固定标题的 v-data-table 的滚动条完美?
- docker - 无法执行命令在 docker 容器中设置环境变量
- c++ - 将类对象直接读入c ++中的向量
- python - 无法将 GPU 与 tensorflow dlerror:libcudnn.so.7 一起使用
- apache-kafka - Kafka Partition Rebalancing 的预期时间是多少?
- raspberry-pi - 如何将我的软件 raid nas 固定在我的树莓派 4 上?
- python - 问题是在列表 x 中找到等于 t 的 2 个连续数字的总和,并返回没有第二个数字的 x 列表
- embedded - esp32 wroom 32 接口 3.5intft,当我初始化 wifi.begin() 时,触摸不起作用
- angular - 页面刷新后,HttpInterceptor 未向后续请求添加新令牌
- python-3.x - multiprocessing.popen_spawn_win32.Popen 对象没有属性'returncode'