suchen

Heim  >  Fragen und Antworten  >  Hauptteil

python3 脚本调用shell 指令如何获得返回值

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

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

Antworte allen(2)Ich werde antworten

  • 迷茫

    迷茫2017-04-18 10:26:50

    怎么没有返回值了

    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,是这里不表,你的需求用这个实现有点复杂,想了解可以去查文档

    Antwort
    0
  • ringa_lee

    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')

    Antwort
    0
  • StornierenAntwort