On Tue, Aug 05, 2014 at 02:53:12PM +0200, Perini Matteo wrote:
> Il 04/08/2014 18:18, Marco Giusti ha scritto:
> >Questo fa' sì che non appena il main loop non ha più niente da fare,
> >chiama la funzione "do_something_with_the_line".
> Ciao
> grazie del suggerimento.
> Sto provando in vari modi ma la situazione migliore che ho ottenuto
> è quella del codice sotto:

Dici di usare le gtk3 e non le usi. Ti suggerisco di usare idle_add e
non lo usi. Adesso ti allego un "canovaccio", vediamo se così va'
meglio.

m.
import time
import threading
# import serial
import gtk
import gobject


class Quit(Exception):
    pass


class Gui:

    def __init__(self, quit):
        self.quit = quit
        win = gtk.Window()
        win.connect("destroy", lambda w: self.exit())
        self.textbuffer = gtk.TextBuffer()
        textview = gtk.TextView(self.textbuffer)
        textview.set_editable(False)
        sw = gtk.ScrolledWindow()
        sw.add(textview)
        win.add(sw)
        win.set_default_size(300, 200)
        win.show_all()

    def exit(self):
        self.quit.set()
        gtk.main_quit()

    def add_text(self, text):
        enditer = self.textbuffer.get_end_iter()
        self.textbuffer.insert(enditer, text)


class Thread2 (threading.Thread):

    def __init__(self, name, gui, quit):
        threading.Thread.__init__(self, name=name)
        self.__gui = gui
        self.__quit = quit
        self.__lines = iter([
            (0, "hello world\n"),
            (1, "bonjour le monde\n"),
            (2, "hallo Welt\n"),
            (4, "ciao mondo\n"),
            (8, "bye\n"),
        ])

    def run(self):
        while not self.__quit.is_set():
            try:
                line = self.readline()
                gobject.idle_add(self.__gui.add_text, line)
            except (EOFError, Quit):
                break

    def readline(self):
        try:
            timeout, line = next(self.__lines)
            t = 0
            while t < timeout and not self.__quit.is_set():
                time.sleep(0.1)
                t += 0.1
            if self.__quit.is_set():
                raise Quit()
            return line
        except StopIteration:
            raise EOFError()

     # def run(self):
     #     self.ser=serial.Serial("/dev/ttyACM0",9600)
     #     while True:
     #         self.a=self.ser.readline()
     #         if self.a!="":
     #             gobject.idle_add(self.stampa, self.a)
     #             while gtk.events_pending():
     #                 gtk.main_iteration()


if __name__ == "__main__":
    gobject.threads_init()
    quit = threading.Event()
    gui = Gui(quit)
    t = Thread2("Serial", gui, quit)
    t.start()
    gtk.main()
_______________________________________________
Python mailing list
Python@lists.python.it
http://lists.python.it/mailman/listinfo/python

Rispondere a