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

相关文章

python遍历目录的方法小结

本文实例总结了python遍历目录的方法。分享给大家供大家参考,具体如下: 方法一使用递归: """ def WalkDir( dir, dir_callback = None, f...

Python wxPython库使用wx.ListBox创建列表框示例

Python wxPython库使用wx.ListBox创建列表框示例

本文实例讲述了Python wxPython库使用wx.ListBox创建列表框。分享给大家供大家参考,具体如下: 如何创建一个列表框? 列表框是提供给用户选择的另一机制。选项被放置在一...

Python中实现输入超时及如何通过变量获取变量名

Python中实现输入超时及如何通过变量获取变量名

背景介绍 开发中遇到了一个需求:程序运行到某处时需要用户确认, 但不能一直傻等, 后面的程序不能被一直阻塞, 需要有个超时限制, 也就是这个程序如果在一段时间后还没有得到用户输入就执行...

Python简单进程锁代码实例

先说说线程 在多线程中,为了保证共享资源的正确性,我们常常会用到线程同步技术. 将一些敏感操作变成原子操作,保证同一时刻多个线程中只有一个线程在执行这个原子操作。 我最常用的是互斥锁,也...

Python import自定义模块方法

python包含子目录中的模块方法比较简单,关键是能够在sys.path里面找到通向模块文件的路径。 下面将具体介绍几种常用情况: (1)主程序与模块程序在同一目录下: 如下面程序结构:...