[issue14243] tempfile.NamedTemporaryFile not particularly useful on Windows

Eryk Sun report at bugs.python.org
Wed Sep 9 14:36:45 EDT 2020


Eryk Sun <eryksun at gmail.com> added the comment:

> For this case, I think the best thing we can probably do is change the 
> default share mode for _all_ opens to include FILE_SHARE_DELETE. 

The C runtime doesn't provide a way to share delete access, except for the O_TEMPORARY flag, so Python would have to re-implement open(). Also, this doesn't help with re-opening a temporary file in another process since most programs do not share file delete access. 

There could be an option to enable a context-manager delete that's independent of closing the file. For example, if delete=True and delete_on_close=False, then _TemporaryFileCloser.close doesn't delete the file. Instead the file would be deleted via os.unlink in _TemporaryFileWrapper.__exit__. The default would be delete=True and delete_on_close=True, which would use the O_TEMPORARY flag in Windows. Combining delete=False with delete_on_close=True would raise a ValueError.

> bringing the default Windows behaviour slightly more in line with 
> how POSIX likes to do things.

In Windows 10, using FILE_SHARE_DELETE is even closer to POSIX behavior when the filesystem is NTFS, which supports POSIX delete semantics by renaming the file to a hidden system directory ("\$Extend\$Deleted") and setting its delete disposition. WinAPI DeleteFileW has been updated to use POSIX semantics if the filesystem supports it:

    >>> f = tempfile.NamedTemporaryFile()
    >>> h = msvcrt.get_osfhandle(f.fileno())
    >>> os.unlink(f.name)
    >>> info = GetFileInformationByHandleEx(h, FileStandardInfo)
    >>> info['DeletePending']
    True
    >>> GetFinalPathNameByHandle(h, 0)
    '\\\\?\\C:\\$Extend\\$Deleted\\001800000002C4F4301F419F'

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue14243>
_______________________________________


More information about the Python-bugs-list mailing list