[英]assigning value to shell variable using a function return value from Python
我有一个Python函数,fooPy()返回一些值。 (int / double或string)
我想使用此值并将其分配给shell脚本。 例如,以下是python函数:
def fooPy():
return "some string"
#return 10 .. alternatively, it can be an int
fooPy()
在shell脚本中,我尝试了以下内容,但它们都不起作用。
fooShell = python fooPy.py
#fooShell = $(python fooPy.py)
#fooShell = echo "$(python fooPy.py)"
您可以在Python中打印您的值,如下所示:
print fooPy()
并在您的shell脚本中:
fooShell=$(python fooPy.py)
请确保不要在shell脚本中的=
周围留出空格。
在Python代码中,您需要打印结果。
import sys
def fooPy():
return 10 # or whatever
if __name__ == '__main__':
sys.stdout.write("%s\n", fooPy())
然后在shell中,你可以这样做:
fooShell=$(python fooPy.py) # note no space around the '='
请注意,我在Python代码中添加了if __name__ == '__main__'
检查,以确保仅在从命令行运行程序时才进行打印,而不是从Python解释器导入程序时。
我也使用sys.stdout.write()
而不是print
,因为
print
在Python 2和Python 3中有不同的行为, sys.stdout.write()
而不是print
:-) 如果你想要Python sys.exit
语句中的值,它将在shell特殊变量$?
。
$ var=$(foo.py)
$ returnval=$?
$ echo $var
Some string
$ echo returnval
10
你应该print
fooPy
返回的值。 shell替换从stdout读取。 用print fooPy()
替换程序的最后一行,然后使用你提到的第二个shell管道。 它应该工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.