|
1 | 1 | # |
2 | | -# Copyright 2012-2021 Ghent University |
| 2 | +# Copyright 2012-2023 Ghent University |
3 | 3 | # |
4 | 4 | # This file is part of vsc-utils, |
5 | 5 | # originally created by the HPC team of Ghent University (http://ugent.be/hpc/en), |
|
32 | 32 | import jsonpickle |
33 | 33 | import os |
34 | 34 | import time |
| 35 | +import pickle |
35 | 36 |
|
36 | 37 | from vsc.utils import fancylogger |
37 | | -from vsc.utils.py2vs3 import pickle, FileNotFoundErrorExc |
38 | | - |
39 | 38 |
|
40 | 39 | class FileCache(object): |
41 | 40 | """File cache with a timestamp safety. |
@@ -106,7 +105,7 @@ def __init__(self, filename, retain_old=True, raise_unpickable=False): |
106 | 105 | finally: |
107 | 106 | g.close() |
108 | 107 |
|
109 | | - except (OSError, IOError, ValueError, FileNotFoundErrorExc) as err: |
| 108 | + except (OSError, IOError, ValueError, FileNotFoundError) as err: |
110 | 109 | self.log.warning("Could not access the file cache at %s [%s]", self.filename, err) |
111 | 110 | self.shelf = {} |
112 | 111 | self.log.info("Cache in %s starts with an empty shelf", (self.filename,)) |
@@ -158,19 +157,17 @@ def close(self): |
158 | 157 | dirname = os.path.dirname(self.filename) |
159 | 158 | if not os.path.exists(dirname): |
160 | 159 | os.makedirs(dirname) |
161 | | - f = open(self.filename, 'wb') |
162 | | - if not f: |
163 | | - self.log.error('cannot open the file cache at %s for writing', self.filename) |
164 | | - else: |
165 | | - if self.retain_old: |
166 | | - self.shelf.update(self.new_shelf) |
167 | | - self.new_shelf = self.shelf |
168 | | - |
169 | | - g = gzip.GzipFile(mode='wb', fileobj=f) |
170 | | - pickled = jsonpickle.encode(self.new_shelf) |
171 | | - # .encode() is required in Python 3, since we need to pass a bytestring |
172 | | - g.write(pickled.encode()) |
173 | | - g.close() |
174 | | - f.close() |
175 | | - |
176 | | - self.log.info('closing the file cache at %s', self.filename) |
| 160 | + with open(self.filename, 'wb') as fih: |
| 161 | + if not fih: |
| 162 | + self.log.error('cannot open the file cache at %s for writing', self.filename) |
| 163 | + else: |
| 164 | + if self.retain_old: |
| 165 | + self.shelf.update(self.new_shelf) |
| 166 | + self.new_shelf = self.shelf |
| 167 | + |
| 168 | + with gzip.GzipFile(mode='wb', fileobj=fih) as zipf: |
| 169 | + pickled = jsonpickle.encode(self.new_shelf) |
| 170 | + # .encode() is required in Python 3, since we need to pass a bytestring |
| 171 | + zipf.write(pickled.encode()) |
| 172 | + |
| 173 | + self.log.info('closing the file cache at %s', self.filename) |
0 commit comments