[pygtk] Threads in PyGTK: keep typing while ping-ing
Mamahita Sela
mamahitasela at yahoo.com
Tue Feb 17 19:27:23 WST 2009
Dear All,
I have read several howtos for threading in PyGTK. I have tried some but with no luck.
What i want is: i can keep typing in gtk.TextView while periodically doing ping some hosts.
I think, the thread part is working since i can ping so fast (even for not reply host, around 3 s for 27 no-reply-host). But, when the ping action is running, i can not typing in textview. What i type while pinging will show up after ping action is done.
(I am using 2.5.1, pygtk 2.10.6 on Linux x86)
This is my code:
import threading
import commands
import gtk
import gobject
gobject.threads_init()
class PingHost(threading.Thread):
def __init__(self, host):
threading.Thread.__init__(self)
self.host = host
self.result = ()
def run(self):
self.result = self.host, commands.getstatusoutput('ping %s -c1' %(self.host))[0]
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):
all_threads = []
#
for h in range(100, 120):
host = '192.168.0.%d' %(h)
#
worker = PingHost(host)
worker.start()
all_threads.append(worker)
#
for t in all_threads:
t.join()
print t.result
#
return True
if __name__ == '__main__':
app = Main()
gtk.main()
PS 1: some friends told me about doing ping in other ways. But, beside ping, i also want to try another case. So, working on thread, imho, is important.
PS 2: I also have tried to not join thread, replacing:
for t in all_threads:
t.join()
print t.result
#
with:
for t in all_threads:
t.join(0.1)
if not t.isAlive():
print t.result
But, then, all i can see is result from host that reply. And, using 0.1s timeout, my GUI is still freezing a little. Any idea?
Any help would be appreciated :)
Best regards,
M
More information about the pygtk
mailing list