Aug-25-2018, 06:24 PM
(This post was last modified: Aug-25-2018, 06:25 PM by Gribouillis.)
I would rather return a sequence of small Service objects for such a program, because Python is very strong at manipulating collections and I think it opens more flexible possibilities. Here is a proposal
from collections import namedtuple import os class Service(namedtuple('Service', 'name status')): __slots__ = () def is_running(self): return self.status == '+' def is_stopped(self): return self.status == '-' def has_no_status(self): return self.status == '?' def service_status_all(): for line in os.popen("service --status-all &> /dev/null"): _, status, _, name = line.strip().split() yield Service(name, status) if __name__ == '__main__': services = list(service_status_all()) print("{} services are available".format(len(services))) for x in services: print(x.name) running = [s for s in services if s.is_running()] print() print("{} services are running".format(len(running))) for y in running: print(y.name) stopped = [s for s in services if s.is_stopped()] print() print("{} services are stopped".format(len(stopped))) for y in stopped: print(y.name)