如何在Python 2.6中使用子进程检查进程?

时间:2017-04-05 18:11:42

标签: python

我有一个shell脚本,我曾经在Linux环境中运行快速进程检查机制。下面只是我正在使用的一段代码。

我们如何在Python中实现同样的目标?我只是搜索并发现使用"子流程"为此目的,模块是否足够好?

Check_ntp () {
    echo "Checking the NTP Service Status on $(uname -n)"
    ps -e | grep ntp > /dev/null 2>&1
    if [ $? -eq 0 ] ; then
    echo "Service Status:  NTP Service is Running"
    else
    echo "Service Status:  NTP Service is Not Running"
    fi
    }

更新

我自己找到了问题的答案:

#!/usr/bin/python

import subprocess
PSNTP = subprocess.call('ps -e| grep ntp > /dev/null 2>&1', shell=True)
if PSNTP == 0:
    print "Status:  NTP Service is Running"
else:
   print "Status:  NTP Service is not Runningg"

PSNSCD = subprocess.call('ps -e | grep nscd > /dev/null 2>&1', shell=True)
if PSNSCD == 0:
   print "Status:  NSCD Service is Running"
else:
   print "Status:  NSCD Service is not Running"

1 个答案:

答案 0 :(得分:1)

我无法弄清楚如何使用subprocess.check_output,但使用subprocess.Popen可以完成这项任务:

import subprocess

cmd1 = ['ps', '-e'] 
cmd2 = ['grep', 'ntp']

proc1 = subprocess.Popen(cmd1,stdout=subprocess.PIPE)
proc2 = subprocess.Popen(cmd2,stdin=proc1.stdout,
                         stdout=subprocess.PIPE,stderr=subprocess.PIPE)

proc1.stdout.close() # Allow proc1 to receive a SIGPIPE if proc2 exits.
out, err=proc2.communicate()

if out:
    print "Service Status:  NTP Service is Running"
else:
    print "Service Status:  NTP Service is Not Running"

# print('out: {0}'.format(out)) # optionally view output
# print('err: {0}'.format(err)) # and any errors