python中有关urllib2和thread的疑问

软件和网站开发以及相关技术探讨
回复
problemshere
帖子: 19
注册时间: 2008-05-04 18:14

python中有关urllib2和thread的疑问

#1

帖子 problemshere » 2009-09-10 19:08

我想利用线程在后台下载网页,而不影响GUI
但问题是:
如果不注释gtk.main()这一行,urllib2.urlopen()不返回。
只有关闭GUI窗口后,urllib2.urlopen()才返回。

此中原因我是在不明白,各位大虾帮忙

代码如下:

代码: 全选

import threading
import gtk
import urllib
import urllib2

class UrlThread(threading.Thread):
        def __init__(self, url):
                threading.Thread.__init__(self)
                self.url = url

        def run(self):
                self.user_agent = 'Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11'
                self.headers = { 'User-Agent' : self.user_agent }

                request = urllib2.Request(self.url, headers=self.headers)

                response = None
                try:
                        response = urllib2.urlopen(request, timeout=10)
                        print response.read()
                except:
                        pass
if __name__ == '__main__':
        test = UrlThread('http://www.baidu.com/')
        test.start()

        window = gtk.Window()
        window.add(gtk.Label('test'))
        window.connect('destroy', gtk.main_quit)
        window.show_all()
        gtk.main()#关键是此行
problemshere
帖子: 19
注册时间: 2008-05-04 18:14

Re: python中有关urllib2和thread的疑问

#2

帖子 problemshere » 2009-09-11 19:42

知道答案了。
只要在gtk.main()前加一句gtk.gdk.threads_init()
即成为这样:
gtk.gdk.threads_init()
gtk.main()
回复