在新线程中加载图像

发布于 2024-10-29 11:51:49 字数 230 浏览 2 评论 0原文

我正在 python 中使用 urllib2 下载图像。这些操作是由计时器调用的,所以有时它会挂起我的程序。是否可以使用 urllib2 和线程?

我当前的代码:

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

那么,如何在新线程中运行此代码?

I'm downloading image with urllib2 in python. The operations is called by timer, so sometimes it hangs my programm. Is it 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦回梦里 2024-11-05 11:51:49

这是我认为您所要求的一个非常基本的示例。是的,正如 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()

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()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文