From b4e5b96a74b5964fb20ef901307aad7def87fdeb Mon Sep 17 00:00:00 2001 From: Michael Tremer Date: Sun, 20 Sep 2020 14:47:40 +0000 Subject: [PATCH] Open all files in a with statement block Signed-off-by: Michael Tremer --- src/collecty/plugins/interface.py | 12 +----------- src/collecty/plugins/memory.py | 10 ++-------- src/collecty/plugins/processor.py | 11 ++--------- 3 files changed, 5 insertions(+), 28 deletions(-) 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): -- 2.47.3