How to return a value python script to bash variab

2019-06-24 23:49发布

问题:

This is a summary of the code:

# import whatever

def createFolder():
    #someCode
    var1=Gdrive.createFolder(name)
    return var1 

def main():
    #someCode
    var2=createFolder()
    return var2

if __name__ == "__main__":
    print main()

One way in which I managed to return a value to a bash variable was printing what was returned from main(). Another way is just printing the variable in any place of the script.
Is there any way to return it in a more pythonic way?

The script is called this way:

folder=$(python create_folder.py "string_as_arg")

回答1:

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.



回答2:

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.



回答3:

Just use sys.exit(), i.e.:

import sys

[...]

if __name__ == "__main__":
    sys.exit(main())


回答4:

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