I am writing a python program which is runs some BASH scripts in sub-processes. One might say that I am using BASH as a scripting language for my python program.
Is there a way to inject python functions into my bash script without having to reload the python code from bash?
strawman example: If this were Python running Javascript, then I could bind my Python functions into the js2py VM and call them from within javascript.
I thought of calling: python some_file_of_mine.py from bash , but this would be launching a new python process, without access to my python program's data.
Also thought of calling: python -c $SOME_INJECTED_PYTHON_CODE. This could use Python's inspect.source() to pre-inject some simple python code along with some bound data from the parent process into the child bash shell. However this will be very quote(`/") sensetive, and will cause some problems with $import.
What I would really like, is a simple way of calling the parent process the bash subprocess, and getting some data back (short of using a Flask + CURL combination)
1 Answer 1
You can send the result of your functions to the standard output by asking the Python interpreter to print the result:
python -c 'import test; print test.get_foo()'
The -c option simply asks Python to execute some Python commands.
In order to store the result in a variable, you can therefore do:
RESULT_FOO=`python -c 'import test; print test.get_foo()'`
or, equivalently
RESULT=$(python -c 'import test; print test.get_foo()')
since backticks and $(...) evaluate a command and replace it by its output.
PS: Getting the result of each function requires parsing the configuration file each time, with this approach. This can be optimized by returning all the results in one go, with something like:
ALL_RESULTS=$(python -c 'import test; print test.get_foo(), test.get_bar()')
The results can then be split and put in different variables with
RESULT_BAR=$(echo $ALL_RESULTS | cut -d' ' -f2)
which takes the second result and puts it in RESULT_BAR for example (and similarly: -fn for result #n).
PS2: it would probably be easier to do everything in a single interpreter (Python, but maybe also the shell), if possible, instead of calculating variables in one program and using them in another one.
python script.py arg1 arg2 ...