I’m trying to monitor a directory, in order to detect when files are added to it and take action, in a Gtk application.
I’ve written the following Gio / Gtk snippet to experiment that, but no event get detected, if I create a file with something like echo tata > tutu
or if I move a file, like mv tutu plop
:
#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gio, Gtk
def directory_changed(monitor, f1, f2, evt):
print("Changed:", f1, f2, evt)
def add_monitor(directory):
gdir = Gio.File.new_for_path(directory)
monitor = gdir.monitor_directory(Gio.FileMonitorFlags.NONE, None)
monitor.connect("changed", directory_changed)
win = Gtk.Window()
win.connect("destroy", Gtk.main_quit)
add_monitor('.')
win.show_all()
Gtk.main()
If it matters, I’m using python3.7 on debian 11 (bullseye) and the python3-gi package version is 3.30.4-1.
Does anyone have an idea of what I’m doing wrong?
2
Answers
I solved my problem with the following snippet which is basically the same, but with a custom class, subclassing Gtk.Window:
But the problem is, I have absolutely no idea of why it works and the previous one doesn't :)
Just from reading the code, I would suggest your first code fails because the add_monitor() de-allocates all its variables when the function exits, unlike the second which keeps them in the object. Although you might want to use self.gdir for the same reason. But perhaps it is not necessary.