python生成器/yield协程/gevent写简单的图片下载器功能示例

yipeiwu_com5年前Python基础

本文实例讲述了python生成器/yield协程/gevent写简单的图片下载器功能。分享给大家供大家参考,具体如下:

1、生成器:

'''第二种生成器'''
# 函数只有有yield存在就是生成器
def test(i):
  while True:
    i += 1
    res = yield i
    print(res)
    i += 1
  return res
def main():
  t = test(1) # 创建生成器对象
  print(next(t)) # next第一次执行从上到下,yield是终点
  print(next(t))
  print(t.send(5))
if __name__ == '__main__':
  main()

运行结果:

2
None
4
5
6

2、yield协程demo:

def run1():
  while True:
    print('run1____')
    yield
def run2():
  while True:
    print('run2____')
    yield
def main():
  while True:
    next(run1())
    next(run2())
if __name__ == '__main__':
  main()

3、gevent写简单的下载图片

import gevent
import requests,lxml
# from gevent import monkey
# monkey.patch_all()
def get_pic(url, list):
  headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'
  }
  response = requests.get(url, headers=headers)
  with open('./pic/'+str(list.pop(0)) + '.png', 'wb') as f:
    f.write(response.content)
def get_pic_name_list():
def main():
  get_pic_name_list()
  list = [x for x in range(9999)]
  gevent.joinall([
    gevent.spawn(get_pic, 'http://pic8.iqiyipic.com/image/20181008/eb/af/v_116880780_m_601_m11_180_236.jpg', list),
    gevent.spawn(get_pic, 'http://pic6.iqiyipic.com/image/20181004/a2/2b/v_112874372_m_601_m15_180_236.jpg', list)
  ])
if __name__ == '__main__':
  main()

更多关于Python相关内容可查看本站专题:《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程

希望本文所述对大家Python程序设计有所帮助。

相关文章

使用opencv将视频帧转成图片输出

使用opencv将视频帧转成图片输出

本文做的是基于opencv将视频帧转成图片输出,由于一个视频包含的帧数过多,经常我们并不是需要它的全部帧转成图片,因此我们希望可以设置每隔多少帧再转一次图片(本文设置为30帧),若有人需...

python交互界面的退出方法

1.在终端输入python,进入之后退出: quit() 或者 exit() 2,进入idle shell下的退出 关闭: quit() 或者 exit() 或...

Python读取YUV文件,并显示的方法

Python读取YUV格式文件,并使用opencv显示的方法 opencv可以读取的图片类型比较多,但大多是比较常见的类型,比如".jpg"和".png",但它不能直接读取YUV格式的文...

Python模拟浏览器上传文件脚本的方法(Multipart/form-data格式)

http协议本身的原始方法不支持multipart/form-data请求,这个请求由原始方法演变而来的。 multipart/form-data的基础方法是post,也就是说是由pos...

利用ImageAI库只需几行python代码实现目标检测

利用ImageAI库只需几行python代码实现目标检测

什么是目标检测 目标检测关注图像中特定的物体目标,需要同时解决解决定位(localization) + 识别(Recognition)。相比分类,检测给出的是对图片前景和背景的理解,我们...