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

时间:2016-12-09 21:24:32

标签: 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()

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

2 个答案:

答案 0 :(得分: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)

(见4.1 Truth Value Testing

答案 1 :(得分:3)

我认为这也是pythonic(但可能只是我)

class NoRunningService(RuntimeError): pass

def findService():
    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:
        raise NoRunningService

def worker():
    while True:
        try:
            service_string = findService()
        except NoRunningService:
            print('Continuing on')
        else:
            print('{} found; skipping'.format(service_string))
        time.sleep(10)