6

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?

Ilyas y.
  • 167
  • 7
Aakash Goyal
  • 1,051
  • 4
  • 12
  • 44

2 Answers2

8

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300
  • 1
    in python, we can use sys.exit(0) for success and sys.exit(1) for failure. – Aakash Goyal Jan 22 '16 at 07:09
  • this_naive_solution_will_not_work_even_with_the_following_modifications=$(python -u some_pyunit_tests.py 2>&1) – Alex Jansen Mar 01 '19 at 04:01
  • @AlexJohnson Huh? Your example will assign the data written by the python script to either file descriptor 1 or 2 (eg stdout and stderr) to the variable on the left hand side. In what way does that not work? – William Pursell Mar 01 '19 at 15:35
  • I don't know, and it's driving me insane. My best guess is that there's some black magic within pyunit that's spawning a separate process which is somehow redirecting output to the terminal from outside the subshell where it was called. Stuff shows up on the screen. I just can't seem to capture it to a file or variable. – Alex Jansen Mar 01 '19 at 19:20
6

Use $(...) to capture a command's stdout as a string.

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

if [[ $output == foobar ]]; then
    do-something
else
    do-something-else
fi
John Kugelman
  • 349,597
  • 67
  • 533
  • 578