我在python中使用urllib2
下载图像。这些操作由计时器调用,因此有时会挂起我的程序。是否可以使用urllib2
和线程?
我目前的代码:
f = open('local-path', 'wb')
f.write(urllib2.urlopen('web-path').read())
f.close()
那么,如何在新线程中运行此代码?
答案 0 :(得分:2)
这是我认为你所要求的一个非常基本的例子。是的,正如RestRisiko所说,urllib2
是线程安全的,如果这实际上是你所要求的。
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()
答案 1 :(得分:1)
urllib2是线程安全的 - 用于记录。