【问题标题】:Get the exit code of a Python script in a Bash script在 Bash 脚本中获取 Python 脚本的退出代码
【发布时间】:2017-06-22 08:10:57
【问题描述】:

我是 Bash 新手,想获取我的 Python 脚本退出代码。

我的script.py 看起来像:

#! /usr/bin/python
def foofoo():
    ret = # Do logic
    if ret != 0:
        print repr(ret) + 'number of errors'
        sys.ext(1)
    else:
        print 'NO ERRORS!!!!'
        sys.exit(0)

def main(argv):
    # Do main stuff
    foofoo()

if __main__ == "__main__":
    main(sys.argv[1:]

我的 Bash 脚本:

#!/bin/bash
python script.py -a a1  -b a2 -c a3
if [ $?!=0 ];
then
    echo "exit 1"
fi
echo "EXIT 0"

我的问题是我总是在我的 Bash 脚本中打印出exit 1。如何在我的 Bash 脚本中获取我的 Python 退出代码?

【问题讨论】:

    标签: python linux bash exit-code


    【解决方案1】:

    空格很重要,因为它们是参数分隔符:

    if [ $? != 0 ];
    then
        echo "exit 1"
    fi
    echo "EXIT 0"
    

    或数字测试-ne。请参阅man [ 了解[ 命令或man bash 了解更多详细信息。

    # Store in a variable. Otherwise, it will be overwritten after the next command
    exit_status=$?
    if [ "${exit_status}" -ne 0 ];
    then
        echo "exit ${exit_status}"
    fi
    echo "EXIT 0"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-14
      • 2011-07-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-28
      • 1970-01-01
      • 2021-08-16
      相关资源
      最近更新 更多