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. docker 下面創建的IMAGE 他們的 ID 一樣?這個是怎么回事????2. 在應用配置文件 app.php 中找不到’route_check_cache’配置項3. html按鍵開關如何提交我想需要的值到數據庫4. css - width設置為100%之后列表無法居中5. ios - vue-cli開發項目webstrom會在stylus樣式報錯,飆紅,請大神幫忙6. css3 - 怎么感覺用 rem 開發的不多啊7. python - 在pyqt中做微信的機器人,要在表格中顯示微信好友的名字,卻顯示不出來,怎么解決?8. html5 - 用Egret寫的小游戲,怎么分享到微信呢?9. javascript - 一個頁面有四個圖片,翻頁的時候想固定住某個圖片然后翻頁,如何實現呢?10. objective-c - 自定義導航條為類似美團的搜索欄樣式
