解決python 執(zhí)行shell命令無法獲取返回值的問題
問題背景:利用python獲取服務(wù)器中supervisor狀態(tài)信息時(shí)發(fā)現(xiàn)未能獲取到返回值。
python獲取執(zhí)行shell命令后返回值得幾種方式:
# 1.os模塊ret = os.popen('supervisorctl status')ret_data = ret.read()# 2.subprocess模塊ret = subprocess.Popen(’supervisorctl status’,shell=True,stdout=subprocess.PIPE)out,err = ret.communicate()# 3.commands模塊ret_data = commands.getoutput('supervisorctl status')# commands.getstatusoutput()還可獲取到命令執(zhí)行是否成功狀態(tài)
一開始程序使用的是 os.popen() 方法,在交互式python shell或者IDE環(huán)境下使用上述方法都可以獲取到執(zhí)行的返回值,但當(dāng)使用腳本執(zhí)行時(shí)發(fā)現(xiàn)返回值為空,然后修改為使用 command.getoutput() 方法,這時(shí)獲取到返回值為 “sh: supervisorctl: command not found”。
由此可知是執(zhí)行命令時(shí)無法識別 supervisorctl 命令,但系統(tǒng)中是已經(jīng)安裝好supervisor的,于是使用 which supervisorctl 查看supervisorctl路徑,以帶路徑的方式執(zhí)行指令 “/usr/local/bin/supervisorctl status”,最后成功獲取到返回值。
總結(jié):
python使用shell命令操作非系統(tǒng)自帶工具時(shí),最好帶上工具路徑。
補(bǔ)充知識:python 如何判斷調(diào)用系統(tǒng)命令是否執(zhí)行成功
首先我們要知道如何調(diào)用系統(tǒng)命令:
>>> os.system(’ls’)anaconda-ks.cfg install.log.syslog 模板 圖片 下載 桌面install.log 公共的 視頻 文檔 音樂0>>>>>> os.system(’lss’)sh: lss: command not found32512>>>
第一種,我們可以肉眼識別正確的會返回0,錯誤的則是非0
第二種,使用if判斷調(diào)用系統(tǒng)命令返回值是否為0,如為0則不輸出,不為0則輸出 'Without the command'
-------------------錯誤-------------------
>>> if os.system(’lss’) !=0:print ’Without the command’... sh: lss: command not foundWithout the command
-------------------正確-------------------
>>> if os.system(’ls’) !=0:print ’Without the command’... anaconda-ks.cfg install.log.syslog 模板 圖片 下載 桌面install.log 公共的 視頻 文檔 音樂>>>
以上這篇解決python 執(zhí)行shell命令無法獲取返回值的問題就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. MyBatis JdbcType 與Oracle、MySql數(shù)據(jù)類型對應(yīng)關(guān)系說明2. jsp網(wǎng)頁實(shí)現(xiàn)貪吃蛇小游戲3. ASP中if語句、select 、while循環(huán)的使用方法4. 存儲于xml中需要的HTML轉(zhuǎn)義代碼5. phpstudy apache開啟ssi使用詳解6. .NET SkiaSharp 生成二維碼驗(yàn)證碼及指定區(qū)域截取方法實(shí)現(xiàn)7. IntelliJ IDEA導(dǎo)入項(xiàng)目的方法8. ASP中實(shí)現(xiàn)字符部位類似.NET里String對象的PadLeft和PadRight函數(shù)9. CentOS郵件服務(wù)器搭建系列—— POP / IMAP 服務(wù)器的構(gòu)建( Dovecot )10. django創(chuàng)建css文件夾的具體方法
