解決python 執(zhí)行shell命令無法獲取返回值的問題
問題背景:利用python獲取服務器中supervisor狀態(tài)信息時發(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í)行的返回值,但當使用腳本執(zhí)行時發(fā)現(xiàn)返回值為空,然后修改為使用 command.getoutput() 方法,這時獲取到返回值為 “sh: supervisorctl: command not found”。
由此可知是執(zhí)行命令時無法識別 supervisorctl 命令,但系統(tǒng)中是已經(jīng)安裝好supervisor的,于是使用 which supervisorctl 查看supervisorctl路徑,以帶路徑的方式執(zhí)行指令 “/usr/local/bin/supervisorctl status”,最后成功獲取到返回值。
總結:
python使用shell命令操作非系統(tǒng)自帶工具時,最好帶上工具路徑。
補充知識:python 如何判斷調用系統(tǒng)命令是否執(zhí)行成功
首先我們要知道如何調用系統(tǒng)命令:
>>> os.system('ls')
anaconda-ks.cfg install.log.syslog 模板 圖片 下載 桌面
install.log 公共的 視頻 文檔 音樂
0
>>>
>>> os.system('lss')
sh: lss: command not found
32512
>>>
\\第一種,我們可以肉眼識別正確的會返回0,錯誤的則是非0
\\第二種,使用if判斷調用系統(tǒng)命令返回值是否為0,如為0則不輸出,不為0則輸出 "Without the command"
-------------------錯誤-------------------
>>> if os.system('lss') !=0:print 'Without the command'
...
sh: lss: command not found
Without the command
-------------------正確-------------------
>>> if os.system('ls') !=0:print 'Without the command'
...
anaconda-ks.cfg install.log.syslog 模板 圖片 下載 桌面
install.log 公共的 視頻 文檔 音樂
>>>
以上這篇解決python 執(zhí)行shell命令無法獲取返回值的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
keras和tensorflow使用fit_generator 批次訓練操作
這篇文章主要介紹了keras和tensorflow使用fit_generator 批次訓練操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07
win10下opencv-python特定版本手動安裝與pip自動安裝教程
這篇文章主要介紹了win10下opencv-python特定版本手動安裝與pip自動安裝教程,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
python des,aes,rsa加解密的實現(xiàn)
這篇文章主要介紹了python des,aes,rsa加解密的實現(xiàn),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2021-01-01
解決PyCharm 中寫 Turtle代碼沒提示以及標黃的問題
這篇文章主要介紹了解決PyCharm 中寫 Turtle代碼沒提示以及標黃的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-03-03
詳解python 條件語句和while循環(huán)的實例代碼
這篇文章主要介紹了詳解python 條件語句和while循環(huán),本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-12-12

