gorakhargosh / watchdog

Python library and shell utilities to monitor filesystem events.
http://packages.python.org/watchdog/
Apache License 2.0
6.64k stars 698 forks source link

FileSystemEventHandler cannot detect changes of files in Windows drives when running from WSL 2 #1072

Open seanballais opened 2 months ago

seanballais commented 2 months ago

NOTE: The issue here is beyond the control of the library authors, so treat this issue as a warning.

Issue

I tried making a program that watches for file changes in a Windows drive. Assume that I have the following file structure, where watchdog_test.py is the main Python script:

.
│─ assets/
│    └─ raw/
│        └─ text/
│            └─ app.txt
└─ watchdog_test.py

watchdog_test.py has the following code:

import time

from watchdog.events import FileSystemEventHandler, FileSystemEvent
from watchdog.observers import Observer

class Handler(FileSystemEventHandler):
    def on_any_event(self, event: FileSystemEvent) -> None:
        print(f':: Something happened to {event.src_path}!')

handler = Handler()
observer = Observer()

observer.schedule(handler, 'assets/raw/text', recursive=True)
observer.start()

try:
    while True:
        time.sleep(1)
except KeyboardInterrupt:
    print('[] Shutting down...')
finally:
    observer.stop()
    observer.join()

For some reason, it sometimes detects file changes when trying to check the current directory (path for the Observer is set to '.'), but not when watching a specific path (just like above). This code, however, works fantastically when running in Windows watching paths in Windows drives (e.g. C:), as well as in Linux (WSL) watching paths in the WSL drives.

Cause

This issue is caused by the lack of support of file notification support in the 9P protocol servers in Windows and WSL[1], which does affect inotify, which watchdog uses in Linux. This prevents watchdog from watching changes in Windows drive paths inside WSL.

Workaround

Use PollingObserver when you're trying to watch files in Windows drives from WSL.

Possible Action Plan

Since this issue is practically unfixable until complete inotify support for files in Windows drives is added, the documentation might have to be updated to let users know about this issue.

References

[1] - https://youtu.be/lwhMThePdIo?si=NW7fBHIQN7iOosKR&t=3166