I have a simple script that checks various Linux processes and, finding one of them, logs a particular message ("particular" in terms of referencing the service's name).
My question: what is the proper, Pythonic way to have a multi-conditional function return a boolean and a string (for use in a printed message)?
Here's a stripped-down version of my current solution (using tuples):
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()
This works, but I care about doing it correctly (stylistically, in particular, but if you glean incorrect logic in this brief sample, please feel free to comment there, too. Appreciate your assistance!