From 8f06d3f9383e4fe0926b5911cc64c52fa01e8c5e Mon Sep 17 00:00:00 2001 From: Ievgenii Meshcheriakov Date: Mon, 12 Jul 2021 11:12:26 +0200 Subject: [PATCH] locale_database: Use NamedTemporaryFile for temporary files Using NamedTemporaryFile instead mkstemp + fdopen simplifies the code. It also makes it easier to switch to using context managers for handling source file modification. Task-number: QTBUG-83488 Pick-to: 6.2 Change-Id: Ibeae840ac6dde3d0b49cd7f985cfa6cd775b7f47 Reviewed-by: Edward Welbourne --- util/locale_database/localetools.py | 21 +++++++-------------- 1 file changed, 7 insertions(+), 14 deletions(-) diff --git a/util/locale_database/localetools.py b/util/locale_database/localetools.py index 82b0848f4a..37b39a07e0 100644 --- a/util/locale_database/localetools.py +++ b/util/locale_database/localetools.py @@ -37,9 +37,8 @@ Classes: SourceFileEditor -- adds standard prelude and tail handling to Transcriber. """ -import os from pathlib import Path -import tempfile +from tempfile import NamedTemporaryFile class Error (Exception): def __init__(self, msg, *args): @@ -85,22 +84,19 @@ class Transcriber (object): def __init__(self, path: Path, temp_dir: Path): # Open the old file self.reader = open(path) - # Create a temp file to write the new data into - temp, tempPath = tempfile.mkstemp(path.name, dir=temp_dir) self.path = path - self.tempPath = Path(tempPath) - self.writer = os.fdopen(temp, "w") + # Create a temp file to write the new data into + self.writer = NamedTemporaryFile('w', prefix=path.name, dir=temp_dir, delete=False) def close(self) -> None: self.reader.close() self.writer.close() - self.reader = self.writer = None # Move the modified file to the original location self.path.unlink() - self.tempPath.rename(self.path) + Path(self.writer.name).rename(self.path) - self.tempPath = None + self.reader = self.writer = None def cleanup(self) -> None: if self.reader: @@ -109,12 +105,9 @@ class Transcriber (object): if self.writer: self.writer.close() - self.writer = None - - if self.tempPath: # Remove temp-file: - self.tempPath.unlink(missing_ok=True) - self.tempPath = None + Path(self.writer.name).unlink(missing_ok=True) + self.writer = None class SourceFileEditor (Transcriber):