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?
I solved my problem with the following snippet which is basically the same, but with a custom class, subclassing Gtk.Window:
#!/usr/bin/env python3
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gio, Gtk
class DocCliWindow(Gtk.Window):
def __init__(self):
Gtk.Window.__init__(self, title = "Document to clipboard")
def on_directory_changed(self, monitor, f1, f2, evt):
print("Changed", f1, f2, evt)
def add_monitor(self, directory):
gdir = Gio.File.new_for_path(directory)
self.monitor = gdir.monitor_directory(Gio.FileMonitorFlags.NONE, None)
self.monitor.connect("changed", self.on_directory_changed)
win = DocCliWindow()
win.connect("destroy", Gtk.main_quit)
win.add_monitor('.')
win.show_all()
Gtk.main()
But the problem is, I have absolutely no idea of why it works and the previous one doesn't :)