如何使用某些键解析日志 - Python

时间:2014-12-11 22:06:59

标签: python regex

我有以下check_status方法:

def check_status(self):
    # each of these is a process I want to make sure they are running.
    status = {
        'pm' : False,
        'om' : False,
        'dm' : False,
        'redis' : False,
    }
    cmd = "sudo %s/foo status" % config.FOO_TOOLS
    output = subprocess.check_output(cmd, shell=True)
    print output
    for k, v in status.iteritems():
        print k

我想根据output的密钥解析status,如果其中一个是Not running,我可以尝试重新启动。我想基于正则表达式来做这件事。 以下是进程未运行时的示例:

[WARN] :  current build mode : debug
app: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
pm : Not running
om : Not running
dm : Not running

相反,这是流程运行的一个例子:

[WARN] :  current build mode : debug
app: USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
pm : root 12337 0.0 0.2 455920 9664 [more crap here]
om : root 12383 0.7 3.1 3256848 114936 [more crap here]
dm : root 12516 11.7 0.4 930316 15508 [more crap here]
[INFO] :  redis [pid=5349] running @ [port:6379]

如何根据现有密钥解析output

1 个答案:

答案 0 :(得分:1)

您可以逐行处理输出,查找所需信息。输出有几个部分,但它很简单,你可以强行使用它而不会使代码太难看。

proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
# skip [WARN]
proc.stdout.readline()
# look for interesting data in remaining
for line in proc.stdout:
    # terminate after processing the [INFO] section
    if line.startswith('[INFO] :  redis'):
        status['redis'] = True
        for line in proc.stdout:
            pass
        break
    # get the process status
    name, remaining = line.split(' ', 1):
    if name in status:
        status[name] = not 'Not running' in remaining
proc.wait()