Collecting return values from python functions in bash
bash, linux, python, shell
Solution
If you don't care about what the python function prints to stdout, you could do this:
$ py_ret_val=$(python -c '
from __future__ import print_function
import sys, try3
print(try3.printTry(), file=sys.stderr)
' 2>&1 1>/dev/null)
$ echo $py_ret_val
true
Problem
I am implementing a bash script that will call a python script's function/method. I want to collect the return valuie of this function into a local variable in the calling bash script. try1.sh contains: ``` #!/bin/sh RETURN_VALUE=`python -c 'import try3; try3.printTry()'` echo $RETURN_VALUE ``` Now the python script: ``` #!/usr/bin/python def printTry(): print 'Hello World' return 'true' ``` on excuting the bash script: ``` $./tr1.sh Hello World ``` there is no 'true' or in that place any other type echoed to stdout as is desired. Another thing I would want to be able to do is, my avtual python code will have around 20-30 functions returning various state values of my software state machine, and I would call these functions from a bash script. In the bash script, I have to store these return values in local variables which are to be used further down the state machine logic implemented in the calling bash script. For each value, I would have do the python -c 'import python_module; python_module.method_name', which would re-enumerate the defined states of the state machine again and again, which I do not want. I want to avoid making the entire python script run just for calling a single function. Is that possible? What possible solutions/suggestions/ideas can be thought of here? I would appreciate the replies. To clarify my intent, the task is to have a part of the bash script replaced by the python script for improving readability. The bash script is really very large(~ 15000 lines), and hence cannot be replaced by a single python script entirely. So parts which can be idetified to be improved can be replaced by python. Also, I had thought of replacing the entire bash script by a python script as suggested by Victor in the comment below, but it wouldn't be feasible in my situation. Hence, I would have to have the state machine divided into bash and python, where python would have some required methods returning state values required by the bash script. Regards, Yusuf Husainy.