python3 腳本調(diào)用shell 指令如何獲得返回值
問(wèn)題描述
python3 腳本中有如下代碼, 但 os.system()方法無(wú)法獲取 shell 指令的返回值, 無(wú)法判斷是否存在nginx的進(jìn)程. 請(qǐng)問(wèn)大神有什么方法可以解決該問(wèn)題?
import osos.system(’netstat -tnlp | grep nginx’)
問(wèn)題解答
回答1:怎么沒(méi)有返回值了
import osif(os.system(’netstat -tnlp | grep nginx’) == 0) { print ’process nginx exists.’}
或者你想說(shuō)的是system不能獲取shell指令輸出的內(nèi)容?那就用popen唄
import osif(os.popen(’netstat -tnlp | grep nginx’).read() != ’’) { print ’process nginx exists.’}
調(diào)用子程序更強(qiáng)大的是subprocess.Popen,是這里不表,你的需求用這個(gè)實(shí)現(xiàn)有點(diǎn)復(fù)雜,想了解可以去查文檔
回答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’)
相關(guān)文章:
1. nignx - docker內(nèi)nginx 80端口被占用2. docker容器呢SSH為什么連不通呢?3. javascript - 連續(xù)點(diǎn)擊觸發(fā)mouseleave事件4. docker - 各位電腦上有多少個(gè)容器啊?容器一多,自己都搞混了,咋辦呢?5. 關(guān)于docker下的nginx壓力測(cè)試6. 關(guān)docker hub上有些鏡像的tag被標(biāo)記““This image has vulnerabilities””7. mac里的docker如何命令行開(kāi)啟呢?8. docker gitlab 如何git clone?9. dockerfile - 我用docker build的時(shí)候出現(xiàn)下邊問(wèn)題 麻煩幫我看一下10. angular.js使用$resource服務(wù)把數(shù)據(jù)存入mongodb的問(wèn)題。

網(wǎng)公網(wǎng)安備