From b92ba0af3e853ccc0c47eaafe72abdd46837f827 Mon Sep 17 00:00:00 2001 From: lumbric Date: Thu, 11 Feb 2021 21:04:36 +0100 Subject: [PATCH] Close files after opening them Using open() as context manager is the preferred way to close files to guarantee exception safety. This commit solves an occasional ResourceWarning, when CylP is used in unit tests run by pytest. There are more direct calls of open() without context manager in setup.py. --- cylp/__init__.py | 3 ++- cylp/py/QP/QP.py | 7 +++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cylp/__init__.py b/cylp/__init__.py index 19f5ffe7..2c7c299f 100644 --- a/cylp/__init__.py +++ b/cylp/__init__.py @@ -1,4 +1,5 @@ import os from os.path import realpath, join currentDir = os.path.dirname(realpath(__file__)) -__version__ = open(join(currentDir, 'VERSION')).read().strip() +with open(join(currentDir, 'VERSION')) as f: + __version__ = f.read().strip() diff --git a/cylp/py/QP/QP.py b/cylp/py/QP/QP.py index 4fbbf534..50f05245 100644 --- a/cylp/py/QP/QP.py +++ b/cylp/py/QP/QP.py @@ -1259,15 +1259,14 @@ def Wolfe(self, method='w'): qobj = 0.5 * x.T * G * x + np.dot(c, x) - self.objectiveOffset print(s.iteration) - f = open('qpout', 'a') - st = '%s %s %s %s %s %s %s\n' % (self.filename.ljust(30), method.ljust(2), + with open('qpout', 'a') as f: + st = '%s %s %s %s %s %s %s\n' % (self.filename.ljust(30), method.ljust(2), str(round(s.objectiveValue, 5)).ljust(8), str(round(qobj, 5)).ljust(8), str(timeToMake), str(timeToSolve), str(timeToMake + timeToSolve)) - f.write(st) - f.close() + f.write(st) # print(checkComp(s.primalVariableSolution['k1'], # s.primalVariableSolution['zk1']))