[pygtk] Threads in PyGTK: keep typing while ping-ing

Mamahita Sela mamahitasela at yahoo.com
Tue Feb 17 23:10:27 WST 2009


Hi Graham,

> Hi Mamahita,
> 
> The problem is that you are calling Thread.join from within
> the main thread.
> This causes the main thread to stop and wait until the
> PingHost threads have
> completed, and so it's not updating the TextView. You
> should use a callback
> to let PingHost return its results. Something like this:
> 
> import threading
> import commands
> import gtk
> import gobject
> 
> gobject.threads_init()
> 
> class PingHost(threading.Thread):
>     def __init__(self, host, callback):
>         threading.Thread.__init__(self)
>         self.host = host
>         self.callback = callback
> 
>     def run(self):
>         result = self.host,
> commands.getstatusoutput('ping %s -c1'
> %(self.host))[0]
>         self.callback(result)
> 
> 
> class Main:
>     def __init__(self):
>         self.win = gtk.Window()
>         self.win.connect('destroy', gtk.main_quit)
>         #
>         self.textb = gtk.TextBuffer()
>         self.textv = gtk.TextView(self.textb)
>         self.textv.set_size_request(500, 500)
>         #
>         self.win.add(self.textv)
>         self.win.show_all()
>         #
>         gobject.timeout_add(5000, self.do_ping)
> 
>     def do_ping(self):
>         for h in range(100, 120):
>             host = '192.168.0.%d' %(h)
>             #
>             worker = PingHost(host, self.ping_result)
>             worker.start()
> 
>             return True
> 
>     def ping_result(self, result):
>         print result
> 
> if __name__ == '__main__':
>   app = Main()
>   gtk.main()
> >

Thank you very much. Your code, sure it helps. 

But, i still found that it only print (many many times) the ping result of first host (which is no reply host). Is this because i did not join all the threads? 

This is what i worry about threading. Should i join the threads manually? 

Please advise,
M


      



More information about the pygtk mailing list