How can I simulate a “locked” file (one which has a write lock)

前端 未结 4 1235
[愿得一人]
[愿得一人] 2021-02-05 09:37

I am trying to debug a problem where users occasionally have locked files which they try to open. The code appears to have correct exception handling but users are still report

4条回答
  •  长情又很酷
    2021-02-05 10:20

    I used LockFileEx function from the Windows API to write a unittest in Python. This worked well for me (shutil.copy() with a locked target fails).

    import win32con
    import win32file
    import pywintypes
    
    p = "yourfile.txt"
    f = file(p, "w")
    hfile = win32file._get_osfhandle(f.fileno())
    flags = win32con.LOCKFILE_EXCLUSIVE_LOCK | win32con.LOCKFILE_FAIL_IMMEDIATELY
    
    win32file.LockFileEx(hfile, flags, 0, 0xffff0000, pywintypes.OVERLAPPED())
    

    See: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365203%28v=vs.85%29.aspx

提交回复
热议问题