我在gtk中使用python。我想下载一个文件,在此过程中,我在窗口上绘制了一个动画gif。但每次下载开始时,gif都会冻结。我认为gobject调用应该可以解决这个问题,但似乎并非如此。
调用是:
在gui类中
...
gobject.timeout_add(3000, self.load)
gtk.main()和load函数:
def load(self):
ul = urllib2.open('http://xxxx/')
data = ul.read()
while gtk.events_pending():
gtk.main_iteration()
return True每次调用加载gui堆栈。有没有办法做得更好?
原始代码:
self.opener = urllib2.build_opener()
self.opener.addheaders.append(('Cookie', self.cookie))
self.state = self.opener.open('http://'+gd_adress+'/state.cst?Lang=en')
self.state_data = self.state.read()发布于 2012-08-22 19:31:19
您需要使用与GObject主循环集成的异步调用。
可能最简单的方法是使用GIO
import gio
f = gio.File(uri='http://xxxx/')
def on_ready(gdaemonfile, result):
data, length, tag = f.load_contents_finish(result)
f.load_contents_async(on_ready)Jono Bacon有一篇很棒的文章:http://www.jonobacon.org/2010/03/15/download-files-async-with-gio-and-python/
不幸的是,据我所知,GIO不支持设置HTTP cookie。在这种情况下,最好的选择可能是使用线程并使用GLib.idle_add将数据返回到主循环,就像在Webkit threads with PyGObject on Gtk3中一样
import threading
import glib
glib.threads_init()
def load_data():
opener = urllib2.build_opener()
opener.addheaders.append(('Cookie', cookie))
state = opener.open('http://'+gd_adress+'/state.cst?Lang=en')
state_data = state.read()
glib.idle_add(on_read_data, state_data)
thread = threading.Thread(target=load_data)
thread.start()其思想是,这将阻塞调用封装在一个线程中,该线程在主线程准备就绪时将数据返回给主线程,因此代码的其余部分可以忽略线程正在使用的事实。
https://stackoverflow.com/questions/12071633
复制相似问题