2

My Python program has a GUI written in GTK 3 (I'm using GTK 3 via from gi.repository import Gtk). I call Gtk.main() to run the GUI. In addition to running the GUI, the program should constantly monitor standard input for incoming commands and write responses to standard output.

What's the proper way to do this with GTK 3 in Python? Is there some way to hook a stdin listener onto Gtk.main()? Can I use Python's standard I/O API to read from sys.stdin and write to sys.stdout or do I need to use some equivalent Glib API? Can I just write my responses to stdout or do I need to care about buffering and hook my output code to some Glib I/O abstraction?

Lassi
  • 3,522
  • 3
  • 22
  • 34

1 Answers1

0

I managed to scrape together a very basic script:

import os
import sys

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GLib, Gtk

logfile = open(os.path.splitext(__file__)[0]+'.log', 'w')

def on_stdin(fobj, cond):
    line = fobj.readline()
    print(repr(line), file=logfile)
    if line == '':
        sys.exit(0)
    return True

win = Gtk.Window()
win.connect('delete-event', Gtk.main_quit)
win.show_all()
GLib.io_add_watch(sys.stdin, GLib.IO_IN, on_stdin)
Gtk.main()

Try piping ls to it. if line == '' is important: if the stream is ready to be read and the read doesn't return any bytes, that means end-of-file. If we don't stop watching the stream on end-of-file, we'll get an endless barrage of calls to on_stdin because Unix considers an end-of-file stream always ready for reading (see Why does poll keep returning although there is no input?)

Lassi
  • 3,522
  • 3
  • 22
  • 34