简体   繁体   English

如何从bash脚本访问python返回值

[英]How to access python return value from bash script

I'm trying to understand how to access from a bash script the return value of a python script. 我试图了解如何从bash脚本访问python脚本的返回值。

Clarifying through an example: 澄清一个例子:

foo.py foo.py

def main():
    print ("exec main..")
    return "execution ok"

if __name__ == '__main__':
    main()

start.sh start.sh

script_output=$(python foo.py 2>&1)
echo $script_output

If I run the bash script, this prints the message "exec main..". 如果我运行bash脚本,则会打印消息“exec main ..”。

How can I store in script_output the return value ( execution ok )? 如何在script_output中存储返回值( 执行正常 )? If I direct execution ok to stdout, the script_output will capture all the stdout (so the 2 print statement). 如果我直接执行ok到stdout,script_output将捕获所有stdout(所以2 print语句)。

Is there any way to implement this? 有没有办法实现这个?

Thanks! 谢谢! Alessio 阿莱西奥

Add a proper exit code from your script using the sys.exit() module. 使用sys.exit()模块从脚本中添加适当的退出代码。 Usually commands return 0 on successful completion of a script. 通常,命令在成功完成脚本后返回0。

import sys

def main():
    print ("exec main..")
    sys.exit(0)

and capture it in shell script with a simple conditional. 并使用简单的条件在shell脚本中捕获它。 Though the exit code is 0 by default and need not be passed explicitly, using sys.exit() gives control to return non-zero codes on error cases wherever applicable to understand some inconsistencies with the script. 虽然退出代码为0默认情况下, 不需要使用显式传递, sys.exit()将控制权交给出错的情况下返回非零代码(如适用),了解一些不一致的脚本。

if python foo.py 2>&1 >/dev/null; then
    echo 'script ran fine'
fi

You can get the previous command's output status through $? 您可以通过$?获取上一个命令的输出状态$? . If the python script ran successfully without any stderr , it should return 0 as exit code else it would return 1 or any number other than 0. 如果python脚本在没有任何stderr情况下成功运行,它应该返回0作为退出代码,否则它将返回1或除0以外的任何数字。

#!/bin/bash
python foo.py 2>&1 /dev/null
script_output=$?
echo $script_output

Bash contains only return code in $? Bash只包含$?返回码$? , so you can't use it to print the text from python's return . ,所以你不能用它来打印python return的文本。 My solution is write in to the stderr in python script, next print only stderr in bash: 我的解决方案是在python脚本中写入stderr,接下来只打印bash中的stderr:

import sys


def main():
    print ("exec main..")
    sys.stderr.write('execution ok\n')
    return "execution ok"

if __name__ == '__main__':
    main()

Bash: 击:

#!/bin/bash

script_output=$(python foo.py 1>/dev/null)
echo $script_output

Output: 输出:

execution ok

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM