亲宝软件园·资讯

展开

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

人气:0

本文实例讲述了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程序设计有所帮助。

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论