【问题标题】:asynchronous downloads with wxpython使用 wxpython 进行异步下载
【发布时间】:2011-07-03 23:20:10
【问题描述】:

好的,我的功能之一是打开一个 url 并读取其内容,然后将其写入文件 问题是当我这样做时,我的 UI 冻结了,我知道我需要使用异步下载,但我似乎不明白该怎么做! 我打开的网址约为 10-20 毫克 http://docs.python.org/library/threading.html 也会以任何方式帮助我吗? 我的代码:

f = open("hello.txt",'wb')
datatowrite = urllib.urlopen(link).read()
f.write(datatowrite)
f.close()

一个例子将不胜感激

谢谢

【问题讨论】:

标签: python wxpython urllib


【解决方案1】:

您可以使用 asynhttp 客户端来执行此操作,因为您不必费心阅读有关线程的文档。

http://code.google.com/p/asynhttp/

【讨论】:

  • 我要了一个例子,但没有人给我一个!,我是编程新手,我不太明白你链接到的页面!
【解决方案2】:

这是一个例子。对asyncDownload 的调用中的10 是以秒为单位的超时时间。你会想要增加它,或者可能完全摆脱它。下载结果存放在thread.dataToWrite下。

import threading
import urllib2 as ul

class asyncDownload(threading.Thread):

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

   def run(self):
      self.dataToWrite = ul.urlopen(self.url,timeout=self.http_timeout).read()


url = 'http://www.yahoo.com'
thread = asyncDownload(url,10)
thread.run()
print('this thread is still running')

【讨论】:

  • 谢谢你的例子,我不知道我是否遗漏了什么,但是当我运行代码并将 url 替换为我拥有的那个时,它似乎除了通常!,我的意思是当我运行代码时,它仍然冻结 python 和 wxpython,这是我试图阻止的,我也玩了超时(10),这似乎没有改变任何东西,我使用 time.time()查看读取文件所需的时间是否存在差异,如果超时为 1 或 100000 则相同!再次感谢您的示例
【解决方案3】:

您需要采用给出的线程示例并将其组合到 wxPython 程序中。你可以使用这个站点上的示例,基本上稍微修改它以使用新的线程示例:http://www.blog.pythonlibrary.org/2010/05/22/wxpython-and-threads/

【讨论】:

    【解决方案4】:

    改编自http://wiki.wxpython.org/LongRunningTasks

    import wx
    import thread
    
    class MainFrame(wx.Frame):
    
        def __init__(self, parent):
            wx.Frame.__init__(self, parent)
    
            self.btn = wx.Button(self, label="Start")
    
            sizer = wx.BoxSizer(wx.VERTICAL)
            sizer.Add(self.btn, proportion=0, flag=wx.EXPAND)
            self.SetSizerAndFit(sizer)
            self.Bind(wx.EVT_BUTTON, self.onButton)
    
        def onButton(self, evt):
            self.btn.Enable(False)
            thread.start_new_thread(self.longRunning, ())
    
        def onLongRunDone(self):
            print "finished my task, I may want to update GUI elements here"
            self.btn.Enable(True)
    
        def longRunning(self):
            f = open("hello.txt",'wb')
            datatowrite = urllib.urlopen(link).read()
            f.write(datatowrite)
            f.close()
            wx.CallAfter(self.onLongRunDone)
    
    if __name__ == "__main__":
        app = wx.PySimpleApp()
        app.TopWindow = MainFrame(None)
        app.TopWindow.Show()
        app.MainLoop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 2014-10-02
      • 1970-01-01
      相关资源
      最近更新 更多