如何让GObject.io_add_watch监控sys.stdout?

时间:2014-09-17 01:33:40

标签: python stdout glib gobject

如何让GObject.io_add_watch监控sys.stdout?

代码:

        GObject.io_add_watch(os.fdopen(self.builder), GObject.IO_IN, self.write_to_buffer)

我试图通过os.fdopen(self.builder)获取我的主要GTK进程的stdout流, 但它提出了例外:

TypeError: an integer is required

能否解释一下我如何正确建议GObject.io_add_watch 观看sys.stdout流?

谢谢!

1 个答案:

答案 0 :(得分:1)

API可让您直接传递sys.stdout,因为它是一个类似文件的对象,使用fileno()方法。但是,它不会正常工作,因为你无法从sys.stdout读取。如果要捕获所有写入stdout的尝试,可以将其替换为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()

运行脚本后"called.txt"的内容:

got hey there
相关问题