Pythonic返回布尔值和消息的方法

ABa*_*ach 7 python linux shell

我有一个简单的脚本来检查各种Linux进程,并找到其中一个,记录一个特定的消息(在引用服务名称方面"特别").

我的问题:使用多条件函数返回布尔值字符串(用于打印消息)的Pythonic方法是什么?

这是我当前解决方案的精简版(使用元组):

import subprocess
import time

def _isProcessRunning(cmd):
    return int(
            subprocess.check_output(
                '{} | grep -v grep | wc -l'.format(cmd),
                shell=True
                )
            ) > 0

def processGroupFound():
    if _isProcessRunning('ps auwxx | grep duplicity'):
        return (True, 'Duplicity')
    elif _isProcessRunning('who | grep pts'):
        return (True, 'SSH')
    elif _isProcessRunning('netstat -na | grep ESTA | grep 5901'):
        return (True, 'VNC')
    else:
        return (False, '')

def worker():
    while True:
        process_found, service_string = processGroupFound()
        if process_found:
            print('{} found; skipping'.format(service_string))
        else:
            print('Continuing on')
        time.sleep(10)


if __name__ == "__main__":
    worker()
Run Code Online (Sandbox Code Playgroud)

这是有效的,但我关心的是正确地做到这一点(特别是风格上,但是如果你在这个简短的样本中收集不正确的逻辑,请随时在那里发表评论.感谢你的帮助!

小智 6

Python中的空字符串是"falsey",因此返回时有点多余(False,'').我可能会这样做:

def processGroupFound():
    if _isProcessRunning('ps auwxx | grep duplicity'):
        return 'Duplicity'
    elif _isProcessRunning('who | grep pts'):
        return 'SSH'
    elif _isProcessRunning('netstat -na | grep ESTA | grep 5901'):
        return 'VNC'
    else:
        return ''

def worker():
    while True:
        service_string = processGroupFound()
        if service_string:
            print('{} found; skipping'.format(service_string))
        else:
            print('Continuing on')
        time.sleep(10)
Run Code Online (Sandbox Code Playgroud)

(参见4.1真值测试)