Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在新线程中加载图像_Python_Multithreading_Urllib2 - Fatal编程技术网

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是

我正在用python下载带有
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()