繁体   English   中英

pygtk和多处理 - 不断更新运行无限循环的另一个进程的textview

[英]pygtk and multiprocessing - Constantly update textview from another process running infinite loop

我正在用pygtk构建一个python应用程序。 它包含一些激活/停用某些无限循环进程的按钮和一个应该继续显示每个进程内部的文本视图。 像冗长的东西。

这些过程还没有结束。 它们仅在用户点击相应按钮(或关闭应用程序)时停止。

出了什么问题:我不能从这些过程中打印textview中的内容。 也许是因为他们没有结束......

实际上应用程序太大了,无法在此显示整个代码。 所以我做了一个简单的例子,说明我在做什么。

import pygtk
pygtk.require("2.0")
import gtk
import time
import glib
from multiprocessing import Process
gtk.threads_init()

class Test(gtk.Window):
    def delete_event(self, widget, event, data=None):
        if isinstance(self.my_process, Process):
            if self.my_process.is_alive():
                self.my_process.terminate()
        gtk.main_quit()
        return False

    def __init__(self):

        gtk.Window.__init__(self)
        self.set_default_size(500, 400)
        self.set_title(u"Test")
        self.connect("delete_event", self.delete_event)

        self.mainBox = gtk.VBox(False, 5)

        self.text = gtk.TextView()
        self.text.set_wrap_mode(gtk.WRAP_WORD)
        self.button = gtk.Button("Start")

        self.add(self.mainBox)
        self.mainBox.pack_start(self.text, True, True, 0)
        self.mainBox.pack_start(self.button, False, True, 0)

        self.button.connect("clicked", self.start_clicked)

        self.show_all()

    def start_clicked(self, widget):
        self.register_data("Starting...")
        self.my_process = Process(target=self.do_something)
        self.my_process.start()

    def do_something(self):
        while True:
            time.sleep(0.5)
            #get a list of a lot of things
            #Do stuff with each item in the list
            #show me on the gui whats going on
            glib.idle_add(self.register_data, "Yo! Here I'm")
            print "Hello, boy."

    def register_data(self, data):
        data = data + "\r\n"
        #gtk.gdk.threads_enter()
        buff = self.text.get_buffer()
        biter = buff.get_start_iter()
        buff.insert(biter, data)
        #gtk.gdk.threads_leave()


if __name__ == "__main__":
    mnc = Test()
    mnc.set_position(gtk.WIN_POS_CENTER)
    gtk.threads_enter()
    gtk.main()
    gtk.threads_leave()

删除所有.threads_init() .threads_enter() .threads_leave() multiprocessing不是threading

将您要显示的数据放入子进程中的multiprocessing.Queue()中:

def do_something(self):
    while True:
        #get a list of a lot of things
        #Do stuff with each item in the list
        #show me on the gui whats going on
        self.data_queue.put("Yo! Here I'm")

并在GUI循环中轮询它:

def __init__(self, ...):
    # ...
    self.data_queue = Queue()
    gobject.timeout_add(100, self.update_text) 

哪里:

def update_text(self):
    # receive updates from the child process here
    try:
        data = self.data_queue.get_nowait()
    except Empty:
        pass # nothing at this time
    else:
        self.register_data(data)
    return True

为了避免轮询,您可以在子进程中写入multiprocessing.Pipe处理。 gobject.io_add_watch()并使用gobject.io_add_watch()设置GUI回调。 这是一个完整的代码示例:

#!/usr/bin/python3
from multiprocessing import Pipe, Process
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import GObject, Gtk

# create GUI to show multiprocessing output
win = Gtk.Window()
win.set_default_size(640, 480)
label = Gtk.Label('process output')
win.add(label)

# start dummy infinite loop in a child process
def loop(conn):
    import itertools, sys, time
    for i in itertools.count():
        conn.send(i)
        time.sleep(0.1 - time.monotonic() % 0.1)

parent_conn, child_conn = Pipe(duplex=False)
Process(target=loop, args=[child_conn], daemon=True).start()
child_conn.close()

# read values from the child
def read_data(source, condition):
    assert parent_conn.poll()
    try:
        i = parent_conn.recv()
    except EOFError:
        return False # stop reading
    # update text
    label.set_text('Result from the child: %03d' % (i,))
    return True # continue reading
# . configure the callback
GObject.io_add_watch(parent_conn.fileno(), GObject.IO_IN, read_data)

win.connect('delete-event', Gtk.main_quit)
win.show_all()
Gtk.main()

您也可以使用任意子进程(不仅仅是python子进程)来完成它

当你在每个调用gtk的线程内部时,你应该使用gtk.threads_enter(),并在调用他之后使用gtk.threads_leave()关闭它。 就像是:

def do_something(self):
        while True:
            time.sleep(0.5)
            gtk.threads_enter()
            #get a list of a lot of things
            #Do stuff with each item in the list
            #show me on the gui whats going on
            glib.idle_add(self.register_data, "Yo! Here I'm")
            gtk.threads_leave()
            print "Hello, boy."

有时您需要使用:

gtk.gdk.threads_init()
gtk.gdk.threads_enter()
#code section
gtk.gdk.threads_leave()

这是一个线程示例 但是非线程非轮询方法会更好,因为在GTK 3中,threads_enter / threads_leave已被弃用,因此您的程序将更难移植到GTK 3 + PyGObject。

在C中,可能会使用g_spawn_async_with_pipes 我认为python中的等价物是glib.spawn_async ,当你要在标准输出中读取数据时,你会使用glib.io_add_watch来通知。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM