[issue46003] os.replace is not cross-platform: at least improve documentation

Eryk Sun report at bugs.python.org
Mon Dec 6 19:47:39 EST 2021


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

The os module tries to avoid documenting low-level OS behaviors. It would be unreliable and difficult to maintain. 

In the case of os.replace(), in Windows it calls MoveFileExW() with the flag MOVEFILE_REPLACE_EXISTING [1]. The source and destination paths must be on the same volume. The caller must have permission to delete the source path and, if it already exists, the destination path. The caller must have permission to add a file or directory to the destination directory. Existing opens of the source path must share delete access. If the source path is a directory, none of the files and directories in its tree is allowed to be open. If the destination path already exists, it cannot be a directory, a readonly file, or mapped as a process image (i.e. a data mapping is allowed, but an executing EXE or DLL is disallowed). Currently, existing opens of the destination path are not allowed, even if they share delete access. 

In Windows 10+, there's new support at the NT system call level (i.e. the layer beneath the Windows API) to support replacing a file that has existing opens, if the file system supports it (e.g. NTFS, ReFS). Delete access is still required, so the opens must share delete access. MoveFileExW() has not been updated yet to use this new capability. If and when it's supported, the requirement for existing opens to share delete access means it won't help in general. Most Windows programs, including Python, do not share delete access on open files. To share delete access in Python, one can use a custom opener function that calls CreateFileW() and wraps the OS handle in an fd via msvcrt.open_osfhandle().

---
[1] https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-movefileexw

----------
nosy: +eryksun

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


More information about the Python-bugs-list mailing list