我在python下写了一个比较字符串的python函数如下:
import time
if name == "__main__":
fo = open("steps.txt", "r+")
steps = fo.read()
print "读取的step是 : ", steps
fo.close()
T0 = 0
X = 600
ticks = time.time()
T = (long(ticks) - T0) / X
step = str(T).upper()
while len(step) < 16:
step = "0" + step
def compare():
if steps == step:
return 1
else:
return 0
compare()
然后我想在shell脚本里调用这个compare.py获取函数return的值
代码如下:
#!/bin/bash
var1=python compare.py
echo $var1
$var1并没有输出我想看到的return值1或0,而是执行了整个py文件
我只想接受这个return值有什么好的方法吗
https://stackoverflow.com/questions/11900828/store-return-value-of-a-python-script-in-a-bash-script
python调用shell脚本的返回值处理几种方式:
shell脚本准备 hello.sh:
echo "hello world!"
echo "succeed";
输出结果:
hello world!
succeed
v_return_status=0
使用os.popen返回结果
无返回终端,只打印输出内容
#------------------------------------------
#二(一)、获取shell print 语句内容一次性打印
#------------------------------------------
p=os.popen('sh hello.sh')
x=p.read()
print x
p.close()
#------------------------------------------
#二(二)、获取shell print 语句内容,按照行读取打印
#------------------------------------------
p=os.popen('sh hello.sh')
x=p.readlines()
for line in x:
print 'ssss='+line
输出结果:
hello world!
succeed
ssss=hello world!
ssss=succeed
3. 使用commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
#------------------------------------------
#三、尝试第三种方案 commands.getstatusoutput() 一个方法就可以获得到返回值和输出,非常好用。
#------------------------------------------
(status, output) = commands.getstatusoutput('sh hello.sh')
print status, output
输出结果:
0 hello world!
succeed