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. python - 獲取到的數據生成新的mysql表2. javascript - js 對中文進行MD5加密和python結果不一樣。3. mysql里的大表用mycat做水平拆分,是不是要先手動分好,再配置mycat4. window下mysql中文亂碼怎么解決??5. sass - gem install compass 使用淘寶 Ruby 安裝失敗,出現 4046. python - (初學者)代碼運行不起來,求指導,謝謝!7. 為啥不用HBuilder?8. python - flask sqlalchemy signals 無法觸發9. python的文件讀寫問題?10. 為什么python中實例檢查推薦使用isinstance而不是type?
