开发者

Load image in new thread

开发者 https://www.devze.com 2023-02-22 05:46 出处:网络
I\'m downloading image with urllib2 in python. The operations is called by timer, so sometimes it hangs my programm. Is it开发者_JAVA百科 possible to work with urllib2 and threads?

I'm downloading image with urllib2 in python. The operations is called by timer, so sometimes it hangs my programm. Is it开发者_JAVA百科 possible to work with urllib2 and threads?

My current code:

f = open('local-path', 'wb')
f.write(urllib2.urlopen('web-path').read())
f.close()

So, how to run this code in new thread?


Here's a very basic example of what I think you've asked for. And yes, as RestRisiko says, urllib2 is thread-safe, if that's actually all you're asking.

import threading
import urllib2
from time import sleep

def load_img(local_path, web_path):
    f = open(local_path, 'wb')
    f.write(urllib2.urlopen(web_path).read())
    f.close()

local_path = 'foo.txt'
web_path = 'http://www.google.com/'

img_thread = threading.Thread(target=load_img, args=(local_path, web_path))
img_thread.start()
while img_thread.is_alive():
    print "doing some other stuff while the thread does its thing"
    sleep(1)
img_thread.join()
0

精彩评论

暂无评论...
验证码 换一张
取 消