thinkchen

python调用shell脚本的返回值处理

python调用shell脚本的返回值处理几种方式:

shell脚本准备 hello.sh:

#! /usr/bin/ssh
echo "hello world!"
echo "succeed";

1. 使用os.system返回执行状态值

#------------------------------------------
#一、执行shell命令的状态返回值
#------------------------------------------
v_return_status=os.system( \'sh hello.sh\')
print "v_return_status=" +str(v_return_status)

输出结果:

hello world!
succeed
v_return_status=0

2. 使用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

 

发表于 2017-05-12 16:59  云之书  阅读(26126)  评论(0编辑  收藏  举报
 

分类:

技术点:

相关文章:

  • 2022-12-23
  • 2021-08-27
  • 2021-08-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-11-22
猜你喜欢
  • 2021-11-20
  • 2022-12-23
  • 2021-07-21
  • 2022-12-23
  • 2021-11-20
  • 2021-11-13
  • 2022-03-06
相关资源
相似解决方案