From d9e45ec703100e06de6136d8035e78222bf74de7 Mon Sep 17 00:00:00 2001 From: Zhenjia Guo Date: Wed, 14 Jun 2023 11:02:06 +0800 Subject: [PATCH] fix pnnx PermissionError (#4801) --- tools/pnnx/README.md | 6 ++---- tools/pnnx/src/ir.cpp | 6 ++---- 2 files changed, 4 insertions(+), 8 deletions(-) diff --git a/tools/pnnx/README.md b/tools/pnnx/README.md index a6d517472..dbf8d052d 100644 --- a/tools/pnnx/README.md +++ b/tools/pnnx/README.md @@ -346,11 +346,9 @@ class Model(nn.Module): return nn.Parameter(self.load_pnnx_bin_as_tensor(archive, key, shape, dtype)) def load_pnnx_bin_as_tensor(self, archive, key, shape, dtype): - _, tmppath = tempfile.mkstemp() - tmpf = open(tmppath, 'wb') - with archive.open(key) as keyfile: + fd, tmppath = tempfile.mkstemp() + with os.fdopen(fd, 'wb') as tmpf, archive.open(key) as keyfile: tmpf.write(keyfile.read()) - tmpf.close() m = np.memmap(tmppath, dtype=dtype, mode='r', shape=shape).copy() os.remove(tmppath) return torch.from_numpy(m) diff --git a/tools/pnnx/src/ir.cpp b/tools/pnnx/src/ir.cpp index e6d902c05..f70fa3872 100644 --- a/tools/pnnx/src/ir.cpp +++ b/tools/pnnx/src/ir.cpp @@ -1785,11 +1785,9 @@ int Graph::python(const std::string& pypath, const std::string& pnnxbinpath) fprintf(pyfp, " return nn.Parameter(self.load_pnnx_bin_as_tensor(archive, key, shape, dtype), requires_grad)\n"); fprintf(pyfp, "\n"); fprintf(pyfp, " def load_pnnx_bin_as_tensor(self, archive, key, shape, dtype):\n"); - fprintf(pyfp, " _, tmppath = tempfile.mkstemp()\n"); - fprintf(pyfp, " tmpf = open(tmppath, 'wb')\n"); - fprintf(pyfp, " with archive.open(key) as keyfile:\n"); + fprintf(pyfp, " fd, tmppath = tempfile.mkstemp()\n"); + fprintf(pyfp, " with os.fdopen(fd, 'wb') as tmpf, archive.open(key) as keyfile:\n"); fprintf(pyfp, " tmpf.write(keyfile.read())\n"); - fprintf(pyfp, " tmpf.close()\n"); fprintf(pyfp, " m = np.memmap(tmppath, dtype=dtype, mode='r', shape=shape).copy()\n"); fprintf(pyfp, " os.remove(tmppath)\n"); fprintf(pyfp, " return torch.from_numpy(m)\n");