Python 在新线程中加载图像
我正在用python下载带有Python 在新线程中加载图像,python,multithreading,urllib2,Python,Multithreading,Urllib2,我正在用python下载带有urllib2的图像。这些操作是由计时器调用的,所以有时它会挂起我的程序。是否可以使用urllib2和线程 我当前的代码: f = open('local-path', 'wb') f.write(urllib2.urlopen('web-path').read()) f.close() 那么,如何在新线程中运行这段代码呢?urllib2是线程安全的——请记录在案。下面是一个非常基本的示例,我认为您已经提出了要求。是的,正如RestRisiko所说,urllib2是
urllib2
的图像。这些操作是由计时器调用的,所以有时它会挂起我的程序。是否可以使用urllib2
和线程
我当前的代码:
f = open('local-path', 'wb')
f.write(urllib2.urlopen('web-path').read())
f.close()
那么,如何在新线程中运行这段代码呢?urllib2是线程安全的——请记录在案。下面是一个非常基本的示例,我认为您已经提出了要求。是的,正如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()