How do I get sys.stdout to be monitored by GObject.io_add_watch?
code:
GObject.io_add_watch(os.fdopen(self.builder), GObject.IO_IN, self.write_to_buffer)
I tried to get the stdout stream of my main GTK process via os.fdopen(self.builder), yet it raises the exception:
TypeError: an integer is required
Could you please explain how I have to properly advise GObject.io_add_watch to watch the sys.stdout stream?
Thanks!
The API will let you pass sys.stdout
directly, since it's a file-like object with a fileno()
method. It won't work right, though, because you can't read from sys.stdout
. If you want to capture all attempts to write to stdout, you can replace it with a pipe
:
import gobject
import sys
import os
def ok(stream, condition):
s = os.fdopen(stream)
data = s.readline()
with open("called.txt", "w") as f:
f.write("got {} ".format(data))
return False
def do_print():
print "hey there"
sys.stdout.flush()
rpipe, wpipe = os.pipe()
wpipe = os.fdopen(wpipe, "w", 0)
sys.stdout = wpipe # Replace sys.stdout
gobject.io_add_watch(rpipe, gobject.IO_IN, ok)
gobject.idle_add(do_print)
gobject.MainLoop().run()
Contents of "called.txt"
after running the script:
got hey there