dsoprea / PyInotify

An efficient and elegant inotify (Linux filesystem activity monitor) library for Python. Python 2 and 3 compatible.
GNU General Public License v2.0
242 stars 73 forks source link

Add support for watching a single file #80

Open chrisinmtown opened 4 years ago

chrisinmtown commented 4 years ago

Extend PyInotify to allow python code to watch just a file.

If I'm reading the Linux system call doc correctly, inotify() supports watching a directory or a file:

https://man7.org/linux/man-pages/man7/inotify.7.html

But adding a watch on a file causes PyInotify to throw an exception:

[Errno 20] Not a directory: '/tmp/file.json/'

Please tell me if I'm missing something obvious? Thanks for considering it.

Agent-Hellboy commented 4 years ago

Hi @chrisinmtown It doesn't work on a single file because, when we use an editor to modify the file, the editor opens a copy of the file and when we save the edited version from the text editor, the existing file is deleted and a new file of the same name is created with the modifications.

When the old file is deleted, the watch created on that file becomes invalid and it is deleted automatically.

You can see the old file being replaced by the new file if you monitor the parent directory. There are two ways to solve it, monitor the parent directory, and print the message when modifications are done to the particular that you want to watch. Else create a new watch on the file whenever modifications are made. When the old file is deleted, the IN_DELETE_SELF event is triggered.

Hopes you get some insight from it. I have just copied and pasted an excerpt from an answer written by someone on StackOverflow. Here is the link for the same: https://stackoverflow.com/questions/13351172/inotify-file-in-c

chrisinmtown commented 4 years ago

I understand that the prereq for monitoring a file with inotify is that it must exist first. I also understand that user-facing editors may do all kinds of strange things.

Anyhow I solved my problem by switching to package notify_simple which supports watching a single file just fine.

jabowery commented 3 years ago

Thanks chrisinmtown. That's what I was looking for and was kind of confused by this package.