assigning value to shell variable using a function return value from Python

后端 未结 4 611
耶瑟儿~
耶瑟儿~ 2020-12-06 05:54

I have a Python function, fooPy() that returns some value. ( int / double or string)

I want to use this value and assign it in a shell script. For example following

4条回答
  •  醉话见心
    2020-12-06 06:55

    In your Python code, you need to print the result.

    import sys
    def fooPy():
        return 10 # or whatever
    
    if __name__ == '__main__':
        sys.stdout.write("%s\n", fooPy())
    

    Then in the shell, you can do:

    fooShell=$(python fooPy.py) # note no space around the '='
    

    Note that I added an if __name__ == '__main__' check in the Python code, to make sure that the printing is done only when your program is run from the command line, not when you import it from the Python interpreter.

    I also used sys.stdout.write() instead of print, because

    • print has different behavior in Python 2 and Python 3,
    • in "real programs", one should use sys.stdout.write() instead of print anyway :-)

提交回复
热议问题