Python watchdog windows wait till copy finishes

前端 未结 7 1049
南笙
南笙 2021-02-05 22:39

I am using the Python watchdog module on a Windows 2012 server to monitor new files appearing on a shared drive. When watchdog notices the new file it kicks off a database resto

7条回答
  •  北海茫月
    2021-02-05 23:31

    I'm using following code to wait until file copied (for Windows only):

    from ctypes import windll
    import time
    
    def is_file_copy_finished(file_path):
        finished = False
    
        GENERIC_WRITE         = 1 << 30
        FILE_SHARE_READ       = 0x00000001
        OPEN_EXISTING         = 3
        FILE_ATTRIBUTE_NORMAL = 0x80
    
        if isinstance(file_path, str):
            file_path_unicode = file_path.decode('utf-8')
        else:
            file_path_unicode = file_path
    
        h_file = windll.Kernel32.CreateFileW(file_path_unicode, GENERIC_WRITE, FILE_SHARE_READ, None, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, None)
    
        if h_file != -1:
            windll.Kernel32.CloseHandle(h_file)
            finished = True
    
        print 'is_file_copy_finished: ' + str(finished)
        return finished
    
    def wait_for_file_copy_finish(file_path):
        while not is_file_copy_finished(file_path):
            time.sleep(0.2)
    
    wait_for_file_copy_finish(r'C:\testfile.txt')
    

    The idea is to try open a file for write with share read mode. It will fail if someone else is writing to it.

    Enjoy ;)

提交回复
热议问题