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 save(filename, contents): fh = open(fi...

分享一下Python 开发者节省时间的10个方法

分享一下Python 开发者节省时间的10个方法

Python 是一个美丽的语言,可以激发用户对它的爱。所以如果你试图加入程序员行列,或者你有点厌倦C++,Perl,Java 和其他语言,我推荐你尝试Python. Python有很多吸...

Python调用C语言的方法【基于ctypes模块】

本文实例讲述了Python调用C语言的方法。分享给大家供大家参考,具体如下: Python中的ctypes模块可能是Python调用C方法中最简单的一种。ctypes模块提供了和C语言兼...

详谈Python中列表list,元祖tuple和numpy中的array区别

1.列表 list是处理一组有序项目的数据结构,即你可以在一个列表中存储一个序列的项目。列表中的项目。列表中的项目应该包括在方括号中,这样python就知道你是在指明一个列表。一旦你创建...

举例详解Python中的split()函数的使用方法

函数:split() Python中有split()和os.path.split()两个函数,具体作用如下: split():拆分字符串。通过指定分隔符对字符串进行切片,并返回分割后的字...