【问题标题】:Exit the shell script from embedded python code从嵌入式 python 代码中退出 shell 脚本
【发布时间】:2019-10-22 01:03:16
【问题描述】:

我想从嵌入的 python 代码中退出 shell 脚本。下面的 os.system() 不起作用,其余的 shell 脚本代码仍在执行。

echo "this is shell code"
a=10
python << END
import os
print "this is python code"

if True:
        print "yes"
        print $a
        os.system("exit 1")
END
echo "I am out of python code"

【问题讨论】:

  • 简答:你不能那样做。
  • 如果 python 脚本(或它调用的任何其他内容)以非零状态退出,您只能通过谷歌搜索 shell 命令 set -e 来获取 shell 退出的一种方法。

标签: python bash shell variables


【解决方案1】:

您必须根据 Python 脚本的结果显式退出 shell。

echo "this is shell code"
a=10
python "$a" <<END || exit
print "this is python code"
if True:
    print "yes"
    print(sys.argv[1])
    sys.exit(1)
END
echo "I am out of python code"

在此示例中,Python 代码以状态 1 无条件退出,最终的 echo 将无法到达,因为非零退出状态将导致 shell 命令 exit 运行。

【讨论】:

    猜你喜欢
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-26
    • 2019-12-29
    • 1970-01-01
    • 1970-01-01
    • 2013-08-28
    相关资源
    最近更新 更多