python3 腳本調用shell 指令如何獲得返回值
問題描述
python3 腳本中有如下代碼, 但 os.system()方法無法獲取 shell 指令的返回值, 無法判斷是否存在nginx的進程. 請問大神有什么方法可以解決該問題?
import osos.system(’netstat -tnlp | grep nginx’)
問題解答
回答1:怎么沒有返回值了
import osif(os.system(’netstat -tnlp | grep nginx’) == 0) { print ’process nginx exists.’}
或者你想說的是system不能獲取shell指令輸出的內容?那就用popen唄
import osif(os.popen(’netstat -tnlp | grep nginx’).read() != ’’) { print ’process nginx exists.’}
調用子程序更強大的是subprocess.Popen,是這里不表,你的需求用這個實現有點復雜,想了解可以去查文檔
回答2:subprocess.getstatusoutput(cmd)
>>> subprocess.getstatusoutput(’ls /bin/ls’)(0, ’/bin/ls’)>>> subprocess.getstatusoutput(’cat /bin/junk’)(256, ’cat: /bin/junk: No such file or directory’)>>> subprocess.getstatusoutput(’/bin/junk’)(256, ’sh: /bin/junk: not found’)
相關文章:
1. sql語句 - 如何在mysql中批量添加用戶?2. shell - Update query wrong in MySQL3. 怎么php怎么通過數組顯示sql查詢結果呢,查詢結果有多條,如圖。4. javascript - mysql插入數據時怎樣避免與庫中的數據重復?5. php - 數據庫表如果是null怎么替換為其他字段的值6. 事務 - mysql共享鎖lock in share mode的實際使用場景7. SQLAlchemy 訪問Mysql數據庫彈出Warning,VARIABLE_VALUE,如何解決?8. mysql - JAVA怎么實現一個DAO同時實現查詢兩個實體類的結果集9. mysql - 數據庫建字段,默認值空和empty string有什么區別 11010. mysql建表報錯,查手冊看不懂,求解?
