From: Michael Tremer Date: Sun, 20 Sep 2020 14:47:40 +0000 (+0000) Subject: Open all files in a with statement block X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b4e5b96a74b5964fb20ef901307aad7def87fdeb;p=collecty.git Open all files in a with statement block Signed-off-by: Michael Tremer --- diff --git a/src/collecty/plugins/interface.py b/src/collecty/plugins/interface.py index b1dfe34..e63f06c 100644 --- a/src/collecty/plugins/interface.py +++ b/src/collecty/plugins/interface.py @@ -233,20 +233,10 @@ class InterfaceObject(base.Object): path = os.path.join(interface_path, "statistics", file) # Open file and read it's content. - f = None - try: - f = open(path) - + with open(path) as f: line = f.readline() line = line.strip() ret.append(line) - except: - ret.append("0") - raise - - finally: - if f: - f.close() return ret diff --git a/src/collecty/plugins/memory.py b/src/collecty/plugins/memory.py index 01e4d66..82791f6 100644 --- a/src/collecty/plugins/memory.py +++ b/src/collecty/plugins/memory.py @@ -90,11 +90,8 @@ class MemoryObject(base.Object): return "default" def collect(self): - f = None - - try: - f = open("/proc/meminfo") - for line in f.readlines(): + with open("/proc/meminfo") as f: + for line in f: if line.startswith("MemTotal:"): total = float(line.split()[1]) if line.startswith("MemFree:"): @@ -121,9 +118,6 @@ class MemoryObject(base.Object): ret.append("0") return ret - finally: - if f: - f.close() class MemoryPlugin(base.Plugin): diff --git a/src/collecty/plugins/processor.py b/src/collecty/plugins/processor.py index bf37b75..11b3aa8 100644 --- a/src/collecty/plugins/processor.py +++ b/src/collecty/plugins/processor.py @@ -109,12 +109,8 @@ class ProcessorObject(base.Object): """ Reads the CPU usage. """ - f = None - - try: - f = open("/proc/stat") - - for line in f.readlines(): + with open("/proc/stat") as f: + for line in f: if not line.startswith("cpu"): continue @@ -131,9 +127,6 @@ class ProcessorObject(base.Object): columns[6], # irq columns[7], # sirq ) - finally: - if f: - f.close() class ProcessorPlugin(base.Plugin):