From 21a30001fa8ee5b68f8304a2c8557b48284807be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 22 Oct 2020 14:31:23 +0200 Subject: [PATCH] =?UTF-8?q?=E2=99=BB=EF=B8=8F=20Py3:=20NamedTemporaryFile?= =?UTF-8?q?=20now=20DOES=20support=20encoding?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/util/__init__.py | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index d8a89ae42..9d214d549 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1155,25 +1155,20 @@ def atomic_write( # Ensure we create the file in the target dir so our move is atomic. See #3719 dir = os.path.dirname(filename) - # NamedTemporaryFile doesn't yet have an encoding parameter in py2, so we go the long way - fd, path = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir) + temp_config = tempfile.NamedTemporaryFile( + mode=mode, prefix=prefix, suffix=suffix, delete=False, encoding=encoding, dir=dir + ) try: - os.close(fd) - - if "b" in mode: - fd = io.open(path, mode=mode) - else: - fd = io.open(path, mode=mode, encoding=encoding) - try: - yield fd + yield temp_config finally: - fd.close() - os.chmod(fd.name, permissions) - shutil.move(fd.name, filename) + temp_config.close() + + os.chmod(temp_config.name, permissions) + shutil.move(temp_config.name, filename) finally: # just in case something went wrong and the temporary file is still there, nuke it now - silent_remove(path) + silent_remove(temp_config.name) @contextlib.contextmanager