返回 bool 值和消息的 Pythonic 方式

标签 python linux shell

<分区>

我有一个简单的脚本来检查各种 Linux 进程,找到其中一个,记录一条特定的消息(“特定”是指引用服务名称)。

我的问题:让多条件函数返回 bool 值 字符串(用于打印消息)的正确 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()

这行得通,但我关心的是正确地完成它(特别是在风格上,但如果您在这个简短的示例中收集到不正确的逻辑,也请随时在那里发表评论。感谢您的帮助!

最佳答案

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)

关于返回 bool 值和消息的 Pythonic 方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41069141/

相关文章:

python - 写入 wav 文件会发出咔嗒声

python多处理卡住

linux - 将文件夹从未知位置移动到服务器上的不同位置

linux - 停止后脚本仍在后台执行

linux - 在 shell 脚本中查找和替换

linux - 使用 shell 脚本从主机名或 FQDN 获取 IP

linux - 如何在多个主机上使用 ssh 和 xargs 运行 bash 脚本而不将脚本复制到每个主机?

python - Django 和 scikit-image 请求超时

python - 我有一个单词的 df,我想知道它们是否在英语词典中

java - 异常在线程 "IDL"java.lang.UnsatisfiedLinkError : no idl_ips in java. library.path