How to return a value from Python script as a Bash variable? How to return a value from Python script as a Bash variable? bash bash

How to return a value from Python script as a Bash variable?


A more pythonic way would be to avoid bash and write the whole lot in python.

You can't expect bash to have a pythonic way of getting values from another process - it's way is the bash way.

bash and python are running in different processes, and inter-process communication (IPC) must go via kernel. There are many IPC mechanisms, but bash does not support them all (shared memory, for example). The lowest common denominator here is bash, so you must use what bash supports, not what python has (python has everything).

Without shared memory, it is not a simple thing to write to variables of another process - let alone another language. Debuggers do it, but they are written specifically for the host language.

The mechanism you use from bash is to capture the stdout of the child process, so python must print. Under the covers this uses an anonymous pipe. You could use a named pipe (also known as a fifo) instead, which python would open as a normal file and write to it. But it wouldn't buy you much.


If you were working in bash then you could simply do:

export var="value"

However, there is no such equivalent in Python. If you try to use os.environ those values will persist for the rest of the process and will not modify anything after the program finishes. Your best bet is to do exactly what you are already doing.


You can try to set an environment variable from within the python code and read it outside, at the bash script. This way looks very elegant to me, but it is definitely not the "perfect solution" or the only solution. If you like this approach, this thread might be useful: How to set environment variables in Python

There are other ways, very similar to what you have done. Check also this thread: store return value of a Python script in a bash script