0

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?

ncarrier
  • 433
  • 3
  • 14

2 Answers2

1

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.

  • I think this is correct. I experienced very similar weirdness with gobject-introspection and GFileMonitor which I eventually realised was because the monitor was being garbage-collected before reaching the call to Gtk.main – telent Apr 04 '22 at 22:21
0

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 :)

ncarrier
  • 433
  • 3
  • 14