使用Python的函数返回值为shell变量赋值

cpp*_*ppb 12 python shell

我有一个Python函数,fooPy()返回一些值.(int/double或string)

我想使用此值并将其分配给shell脚本.例如以下是python函数:

def fooPy():
    return "some string" 
    #return 10  .. alternatively, it can be an int

fooPy()
Run Code Online (Sandbox Code Playgroud)

在shell脚本中,我尝试了以下内容,但它们都不起作用.

fooShell = python fooPy.py
#fooShell = $(python fooPy.py)
#fooShell = echo "$(python fooPy.py)"
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 34

您可以在Python中打印您的值,如下所示:

print fooPy()
Run Code Online (Sandbox Code Playgroud)

并在您的shell脚本中:

fooShell=$(python fooPy.py)
Run Code Online (Sandbox Code Playgroud)

请确保不要=在shell脚本中留下空格.


Alo*_*hal 11

在Python代码中,您需要打印结果.

import sys
def fooPy():
    return 10 # or whatever

if __name__ == '__main__':
    sys.stdout.write("%s\n", fooPy())
Run Code Online (Sandbox Code Playgroud)

然后在shell中,你可以这样做:

fooShell=$(python fooPy.py) # note no space around the '='
Run Code Online (Sandbox Code Playgroud)

请注意,我if __name__ == '__main__'在Python代码中添加了一个检查,以确保仅在从命令行运行程序时才进行打印,而不是从Python解释器导入程序时.

我也用sys.stdout.write()而不是print,因为

  • print 在Python 2和Python 3中有不同的行为,
  • 在"真实的程序"中,应该使用sys.stdout.write()而不是print反正:-)


Pau*_*ce. 5

如果你想要Python sys.exit语句中的值,它将在shell特殊变量中$?.

$ var=$(foo.py)
$ returnval=$?
$ echo $var
Some string
$ echo returnval
10
Run Code Online (Sandbox Code Playgroud)