Skip to content

Commit d9e45ec

Browse files
authored
fix pnnx PermissionError (#4801)
1 parent 4a78b6d commit d9e45ec

File tree

2 files changed

+4
-8
lines changed

2 files changed

+4
-8
lines changed

tools/pnnx/README.md

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -346,11 +346,9 @@ class Model(nn.Module):
346346
return nn.Parameter(self.load_pnnx_bin_as_tensor(archive, key, shape, dtype))
347347

348348
def load_pnnx_bin_as_tensor(self, archive, key, shape, dtype):
349-
_, tmppath = tempfile.mkstemp()
350-
tmpf = open(tmppath, 'wb')
351-
with archive.open(key) as keyfile:
349+
fd, tmppath = tempfile.mkstemp()
350+
with os.fdopen(fd, 'wb') as tmpf, archive.open(key) as keyfile:
352351
tmpf.write(keyfile.read())
353-
tmpf.close()
354352
m = np.memmap(tmppath, dtype=dtype, mode='r', shape=shape).copy()
355353
os.remove(tmppath)
356354
return torch.from_numpy(m)

tools/pnnx/src/ir.cpp

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1785,11 +1785,9 @@ int Graph::python(const std::string& pypath, const std::string& pnnxbinpath)
17851785
fprintf(pyfp, " return nn.Parameter(self.load_pnnx_bin_as_tensor(archive, key, shape, dtype), requires_grad)\n");
17861786
fprintf(pyfp, "\n");
17871787
fprintf(pyfp, " def load_pnnx_bin_as_tensor(self, archive, key, shape, dtype):\n");
1788-
fprintf(pyfp, " _, tmppath = tempfile.mkstemp()\n");
1789-
fprintf(pyfp, " tmpf = open(tmppath, 'wb')\n");
1790-
fprintf(pyfp, " with archive.open(key) as keyfile:\n");
1788+
fprintf(pyfp, " fd, tmppath = tempfile.mkstemp()\n");
1789+
fprintf(pyfp, " with os.fdopen(fd, 'wb') as tmpf, archive.open(key) as keyfile:\n");
17911790
fprintf(pyfp, " tmpf.write(keyfile.read())\n");
1792-
fprintf(pyfp, " tmpf.close()\n");
17931791
fprintf(pyfp, " m = np.memmap(tmppath, dtype=dtype, mode='r', shape=shape).copy()\n");
17941792
fprintf(pyfp, " os.remove(tmppath)\n");
17951793
fprintf(pyfp, " return torch.from_numpy(m)\n");

0 commit comments

Comments
 (0)