溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

python執(zhí)行shell命令無法獲取返回值如何解決

發(fā)布時間:2020-12-07 15:21:20 來源:億速云 閱讀:392 作者:Leah 欄目:開發(fā)技術(shù)

本篇文章為大家展示了python執(zhí)行shell命令無法獲取返回值如何解決,內(nèi)容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細(xì)介紹希望你能有所收獲。

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í)行時發(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”,最后成功獲取到返回值。

總結(jié):

python使用shell命令操作非系統(tǒng)自帶工具時,最好帶上工具路徑。

補(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 found
32512
>>>

\\第一種,我們可以肉眼識別正確的會返回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 found
Without the command

-------------------正確-------------------

>>> if os.system('ls') !=0:print 'Without the command'
...
 
anaconda-ks.cfg install.log.syslog 模板 圖片 下載 桌面
install.log     公共的           視頻 文檔 音樂
>>>

上述內(nèi)容就是python執(zhí)行shell命令無法獲取返回值如何解決,你們學(xué)到知識或技能了嗎?如果還想學(xué)到更多技能或者豐富自己的知識儲備,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI