python3 脚本中有如下代码, 但 os.system()方法无法获取 shell 指令的返回值, 无法判断是否存在nginx的进程. 请问大神有什么方法可以解决该问题?
import os
os.system('netstat -tnlp | grep nginx')
迷茫2017-04-18 10:26:50
Why is there no return value?
import os
if(os.system('netstat -tnlp | grep nginx') == 0) {
print 'process nginx exists.'
}
Or what you want to say is that system cannot obtain the content output by the shell command? Then use popen
import os
if(os.popen('netstat -tnlp | grep nginx').read() != '') {
print 'process nginx exists.'
}
The more powerful thing about calling subroutines is subprocess.Popen
, which is not listed here. Your needs are a bit complicated to implement with this method. If you want to know more, you can check the documentation
ringa_lee2017-04-18 10:26:50
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')