python3 脚本调用shell 指令如何获得返回值
天蓬老师
天蓬老师 2017-04-18 10:24:50
0
2
582

python3 脚本中有如下代码, 但 os.system()方法无法获取 shell 指令的返回值, 无法判断是否存在nginx的进程. 请问大神有什么方法可以解决该问题?

import os
os.system('netstat -tnlp | grep nginx')
天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(2)
迷茫

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

左手右手慢动作

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')
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template