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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python内置函数Type()函数一个有趣的用法

今天在网上看到type的一段代码 ,然后查了一下文档,才知道type还有三个参数的用法。 http://docs.python.org/2/library/functions.html...

python实现数通设备端口监控示例

最近因工作需要,上面要求,每天需上报运维的几百数通设备端口使用情况【】,虽然有现成网管监控工具监控设备状态,但做报表,有点不方便,特写了个小脚本。注:测试运行于ubuntn,需安装snm...

Python中的heapq模块源码详析

Python中的heapq模块源码详析

起步 这是一个相当实用的内置模块,但是很多人竟然不知道他的存在——笔者也是今天偶然看到的,哎……尽管如此,还是改变不了这个模块好用的事实 heapq 模块实现了适用于Python列表的...

Python之指数与E记法的区别详解

不要把自乘得到幂(也称为求幂)和E记法弄混了 3**5表示3的5次幂,也就是3*3*3*3*3,等于243 3e5表示3乘以10的5次幂,也就是3*10*10*10*10*10,结果等于...

Python实现判断给定列表是否有重复元素的方法

Python实现判断给定列表是否有重复元素的方法

本文实例讲述了Python实现判断给定列表是否有重复元素的方法。分享给大家供大家参考,具体如下: 题目很简单,只是简单温习一个方法,most_common,这是collection模块中...