在bash脚本中返回Python脚本的退出编号和值

2024-04-26 12:38:11 发布

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

我想从bash脚本执行python脚本,并将python脚本的输出存储在一个变量中。你知道吗

在python脚本中,我打印了一些值为0或1的错误消息

def main (): 
      if condition A :
            sys.stderr.write("FORBIDDEN commit")
            return 1
      else: return 0
sys.exit(main())

这是我的bash脚本:

我使用$?从python脚本获取退出代码+错误值

python  /var/www/svn/TEST/hooks/pre-commit-standard-codeline.py $SVNRepository $SVNTransaction
PYTHONRESULT=$?

echo $PYTHONRESULT >&2     #echo display -->FORBIDDEN commit1


if [ $PYTHONRESULT -ne 0 ];
        then
        echo -e "\n"                                                                 >&2
        echo "=====================================================================" >&2
        echo "Your commit is blocked for the following reasons:"                     >&2
        echo -e "\n"                                                                 >&2
        echo -e ${PYTHONRESULT:0}                                                              >&2
        echo -e "\n"                                                                 >&2
        echo "=====================================================================" >&2
        echo -e "\n"
        exit 1
fi

我的问题是在bash脚本中,我想从错误消息中拆分python的exit值,这样就可以在echo命令中触发结果

我试过${PYTHONRESULT:0},但它总是给出python脚本的退出值


Tags: echo脚本bash消息returnifmaindef
1条回答
网友
1楼 · 发布于 2024-04-26 12:38:11

你好像不知道什么会去哪里。Python已经将错误消息写入standard error,return代码结束于shell中的$?。你知道吗

通常,您不需要经常显式地检查$?,因为ifwhile以及朋友在幕后为您做这些。你知道吗

也许你要找的只是

if python  /var/www/svn/TEST/hooks/pre-commit-standard-codeline.py "$SVNRepository" "$SVNTransaction"; then
    : all good, do nothing
    pythonresult=0
else
    # error message from Python will already have been printed on stderr
    # use lower case for your private variables
    pythonresult=$?
    cat <<-____eof >&2
        $0: Obnoxiously long error message.
        $0: The longer you make it, the less people will read it
            and the more actually useful information scrolls off the screen.
        $0: Python result code was $pythonresult!!!!11!
____eof
fi
exit $pythonresult

如果要捕获标准错误,请尝试

if captured=$(python ... 2>&1); then
    # mostly as above
    pythonresult=0
    # etc
else
    # mostly as above
    pythonresult=$?
    # etc
    # but you can use "$captured" to show stderr from Python
    # with whatever embellishments and screaming you want
fi

这有点混乱,因为它混合了标准输出和标准误差。你知道吗

如果需要的话,有很多方法可以将它们分开,但是你的问题和代码看起来好像你并不期望在标准输出上得到任何东西。你知道吗

相关问题 更多 >