久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術文章
文章詳情頁

解決python 執行shell命令無法獲取返回值的問題

瀏覽:57日期:2022-07-03 09:59:53

問題背景:利用python獲取服務器中supervisor狀態信息時發現未能獲取到返回值。

python獲取執行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()還可獲取到命令執行是否成功狀態

一開始程序使用的是 os.popen() 方法,在交互式python shell或者IDE環境下使用上述方法都可以獲取到執行的返回值,但當使用腳本執行時發現返回值為空,然后修改為使用 command.getoutput() 方法,這時獲取到返回值為 “sh: supervisorctl: command not found”。

由此可知是執行命令時無法識別 supervisorctl 命令,但系統中是已經安裝好supervisor的,于是使用 which supervisorctl 查看supervisorctl路徑,以帶路徑的方式執行指令 “/usr/local/bin/supervisorctl status”,最后成功獲取到返回值。

總結:

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

補充知識:python 如何判斷調用系統命令是否執行成功

首先我們要知道如何調用系統命令:

>>> os.system(’ls’)anaconda-ks.cfg install.log.syslog 模板 圖片 下載 桌面install.log 公共的 視頻 文檔 音樂0>>>>>> os.system(’lss’)sh: lss: command not found32512>>>

第一種,我們可以肉眼識別正確的會返回0,錯誤的則是非0

第二種,使用if判斷調用系統命令返回值是否為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 執行shell命令無法獲取返回值的問題就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持好吧啦網。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 获嘉县| 阿荣旗| 自治县| 奉节县| 徐州市| 宣恩县| 洞口县| 黄冈市| 分宜县| 吉安市| 迁西县| 陆川县| 青田县| 芜湖市| 延长县| 大冶市| 玉树县| 安福县| 黎平县| 方正县| 宜昌市| 忻城县| 武义县| 田阳县| 勃利县| 革吉县| 林西县| 龙州县| 泊头市| 嘉兴市| 泽库县| 定结县| 绵竹市| 康马县| 陕西省| 叶城县| 榆中县| 奉化市| 广河县| 青铜峡市| 黎城县|