Call python from shell and capture output

Gauranga picture Gauranga · Jan 22, 2016 · Viewed 9.4k times · Source

I have written a program in shell. And inside this shell script, I am calling a python script. That is working fine. I want my python script to return the output to the shell script. Is it possible? (I didnt get any such way on google). Can you please tell how to do that in case it is possible?

test.sh

#!/bin/bash
python call_py.py

and python script (call_py.py)

#!/usr/bin/python
if some_check:
    "return working"
else:
    "return not working"

How do I return from python and catch in shell?

Answer

William Pursell picture William Pursell · Jan 22, 2016

To get the output of a command in a variable, use process substitution:

var=$( cmd )

eg

var=$( ls $HOME )

or

var=$( python myscript.py)

The $() is (almost) exactly equivalent to using backticks, but the backticks syntax is deprecated and $() is preferred.

If your intent is to return a string 'working' or 'not working' and use that value in the shell script to determine whether or not the python script was successful, change your plan. It is much better to use a return value. eg, in python you 'return 0' or 'return 1' (zero for success, 1 for failure), and then the shell script is simply:

if python call_py.py; then
  echo success
else
  echo failure
fi