Skip to content

Commit 78fecbf

Browse files
Bastian-KrauseEmantor
authored andcommitted
util/atomic: fix UnboundLocalError in atomic_replace()
If the temporary file cannot get created.. Traceback (most recent call last): File "labgrid/util/atomic.py", line 6, in atomic_replace with tempfile.NamedTemporaryFile( File "/usr/lib/python3.9/tempfile.py", line 680, in NamedTemporaryFile (fd, name) = _mkstemp_inner(dir, prefix, suffix, flags, output_type) File "/usr/lib/python3.9/tempfile.py", line 390, in _mkstemp_inner fd = _os.open(file, flags, 0o600) OSError: [Errno 30] Read-only file system: 'tmpgvplm6ok' ..the variable `f` is not assigned.. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "labgrid/remote/coordinator.py", line 292, in poll await self._poll_step() File "labgrid/remote/coordinator.py", line 258, in _poll_step await self.save() File "labgrid/remote/coordinator.py", line 312, in save await loop.run_in_executor(None, atomic_replace, 'resources.yaml', resources) File "/usr/lib/python3.9/concurrent/futures/thread.py", line 52, in run result = self.fn(*self.args, **self.kwargs) File "labgrid/util/atomic.py", line 16, in atomic_replace os.unlink(f.name) UnboundLocalError: local variable 'f' referenced before assignment While this situation stems from a configuration error, we should still avoid UnboundLocalErrors. Fix this by setting f initially to None and check for this in the finally clause. Signed-off-by: Bastian Krause <bst@pengutronix.de> (cherry picked from commit 7e0a144) Signed-off-by: Rouven Czerwinski <r.czerwinski@pengutronix.de>
1 parent bd54e94 commit 78fecbf

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

labgrid/util/atomic.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import tempfile
33

44
def atomic_replace(filename, data):
5+
f = None
56
try:
67
with tempfile.NamedTemporaryFile(
78
mode='wb',
@@ -12,7 +13,8 @@ def atomic_replace(filename, data):
1213
os.fsync(f.fileno())
1314
os.replace(f.name, filename)
1415
finally:
15-
try:
16-
os.unlink(f.name)
17-
except FileNotFoundError:
18-
pass
16+
if f is not None:
17+
try:
18+
os.unlink(f.name)
19+
except FileNotFoundError:
20+
pass

0 commit comments

Comments
 (0)