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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM