Python tempfile.TemporaryFile hangs on Windows when no write privilege

﹥>﹥吖頭↗ 提交于 2019-12-05 19:05:22

A deeper dive than I'd initially done, turned up the answer. This is indeed a Python bug, reported some time ago but which remains to be addressed.

The comments from eryksun describe the details -- and it's what prompted me to take a closer look at the Python bug database -- so ultimately that's where credit is due. I'm just filling it in here to get the question answered and closed out.

The bug affects only Windows environments, but unfortunately it has the result of rendering tempfile.TemporaryFile unusable on Windows for this common use case.

I would suggest replacing usage of NamedTemporaryFile with os.path.join(tempfile.gettempdir(), os.urandom(32).hex()).

It's safer, faster, and cross-platform. Only fails on FAT or DOS systems, which isn't a problem for most people anymore.

Here's a compatible version:

import os, tempfile, gc


class TemporaryFile:
    def __init__(self, name, io, delete):
        self.name = name
        self.__io = io
        self.__delete = delete

    def __getattr__(self, k):
        return getattr(self.__io, k)

    def __del__(self):
        if self.__delete:
            os.unlink(self.name)


def NamedTemporaryFile(mode='w+b', bufsize=-1, suffix='', prefix='tmp', dir=None, delete=True):
    if not dir:
        dir = tempfile.gettempdir()
    name = os.path.join(dir, prefix + os.urandom(32).hex() + suffix)
    fh = open(name, "w+b", bufsize)
    if mode != "w+b":
        fh.close()
        fh = open(name, mode)
    return TemporaryFile(name, fh, delete)

..and here's a module with tests:

https://gist.github.com/earonesty/a052ce176e99d5a659472d0dab6ea361

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!