从shell调用python并捕获输出

Gau*_*nga 6 shell function-call python-2.7

我已经在shell中编写了一个程序.在这个shell脚本中,我正在调用一个python脚本.这工作正常.我希望我的python脚本将输出返回到shell脚本.可能吗?(我没有在谷歌上得到任何这样的方式).如果有可能,你能告诉我该怎么做吗?

test.sh

#!/bin/bash
python call_py.py
Run Code Online (Sandbox Code Playgroud)

和python脚本(call_py.py)

#!/usr/bin/python
if some_check:
    "return working"
else:
    "return not working"
Run Code Online (Sandbox Code Playgroud)

如何从python返回并捕获shell?

Joh*_*ica 6

用于$(...)将命令的标准输出捕获为字符串。

output=$(./script.py)
echo "output was '$output'"

if [[ $output == foobar ]]; then
    do-something
else
    do-something-else
fi
Run Code Online (Sandbox Code Playgroud)


Wil*_*ell 6

要在变量中获取命令的输出,请使用进程替换:

var=$( cmd )
Run Code Online (Sandbox Code Playgroud)

例如

var=$( ls $HOME )
Run Code Online (Sandbox Code Playgroud)

要么

var=$( python myscript.py)
Run Code Online (Sandbox Code Playgroud)

$()(几乎)完全等同于使用反引号,但不推荐使用反引号语法,而首选$().

如果您的意图是返回字符串'working'或'not working'并在shell脚本中使用该值来确定python脚本是否成功,请更改您的计划.使用返回值要好得多.例如,在python中你'返回0'或'返回1'(成功为0,失败为1),然后shell脚本就是:

if python call_py.py; then
  echo success
else
  echo failure
fi
Run Code Online (Sandbox Code Playgroud)