在新线程中加载图像

2 投票
1 回答
770 浏览
提问于 2025-04-16 14:59

我正在用 urllib2 在 Python 中下载图片。这个操作是通过定时器来调用的,所以有时候会导致我的程序卡住。请问可以用 urllib2 和线程一起工作吗?

我现在的代码是:

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

那么,怎么才能在新线程中运行这段代码呢?

1 个回答

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()

撰写回答