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

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

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

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

Antworte allen(2)
迷茫

怎么没有返回值了

import os
if(os.system('netstat -tnlp | grep nginx') == 0) {
    print 'process nginx exists.'
}

或者你想说的是system不能获取shell指令输出的内容?那就用popen呗

import os
if(os.popen('netstat -tnlp | grep nginx').read() != '') {
    print 'process nginx exists.'
}

调用子程序更强大的是subprocess.Popen,是这里不表,你的需求用这个实现有点复杂,想了解可以去查文档

左手右手慢动作

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')
Beliebte Tutorials
Mehr>
Neueste Downloads
Mehr>
Web-Effekte
Quellcode der Website
Website-Materialien
Frontend-Vorlage
Über uns Haftungsausschluss Sitemap
Chinesische PHP-Website:Online-PHP-Schulung für das Gemeinwohl,Helfen Sie PHP-Lernenden, sich schnell weiterzuentwickeln!