我有一个简单的脚本,可以检查各种Linux进程,并找到其中一个脚本记录了一条特定的消息(在引用该服务的名称方面"特定")。
我的问题:拥有多条件函数返回boolean 和 a String的正确的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真实价值测试)
我认为这也是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)