python asyncio 总结(一)

import asyncio, threading
import aiohttp

class Tasks():

    def __init__(self, max_async, loop=None):

        self.loop = loop or asyncio.get_event_loop()
        self._queue = asyncio.Queue(maxsize=100, loop=self.loop)
        self.lock = threading.Lock()
        self.max_async = max_async
        self.work_list = []

    async def geturldata(self, url):
        print(url)
        try:
            async with aiohttp.ClientSession(loop=self.loop, conn_timeout=1) as s:
                resp = await s.get(url)
                result = await resp.read()
                print(result.decode(‘utf-8‘))
        except Exception as e:
            print(e)

    async def run(self):
        #ensure_future将协程转换成任务,并投递到事件循环

        works = [asyncio.ensure_future(self.work(), loop=self.loop) for _ in range(self.max_async)]
        self.work_list.extend(works)
        await self._queue.join()
        print(‘all tasks done‘)
        for w in works:
            w.cancel() #任务并不会立刻变为取消的状态,而是要等到下次的事件循环
    async def work(self):
        try:
            while True:
                url = await self._queue.get()

                await self.geturldata(url)
                self._queue.task_done()
        except asyncio.CancelledError: pass
    def addtask(self, item):
        with self.lock:
            self._queue.put_nowait(item)

    @property
    def count(self):
        return self._queue.qsize()
    def printstatus(self):
        for w in self.work_list:
            print(w.done())

t = Tasks(max_async=10)
url = ‘https://www.baidu.com‘
for u in range(100):
    t.addtask(url)
print(t.count)
loop = asyncio.get_event_loop()
loop.run_until_complete(t.run())
t.printstatus()
loop.close()

原文地址:https://www.cnblogs.com/alplf123/p/8549063.html

时间: 2024-08-30 18:31:08

python asyncio 总结(一)的相关文章

python asyncio异步代理池

使用python asyncio实现了一个异步代理池,根据规则爬取代理网站上的免费代理,在验证其有效后存入redis中,定期扩展代理的数量并检验池中代理的有效性,移除失效的代理.同时用aiohttp实现了一个server,其他的程序可以通过访问相应的url来从代理池中获取代理. 源码 Github 环境 Python 3.5+ Redis PhantomJS(可选) Supervisord(可选) 因为代码中大量使用了asyncio的async和await语法,它们是在Python3.5中才提供

Python asyncio库的学习和使用

因为要找工作,把之前自己搞的爬虫整理一下,没有项目经验真蛋疼,只能做这种水的不行的东西...T  T,希望找工作能有好结果. 之前爬虫使用的是requests+多线程/多进程,后来随着前几天的深入了解,才发现,对于爬虫来说,真正的瓶颈并不是CPU的处理速度,而是对于网页抓取时候的往返时间,因为如果采用requests+多线程/多进程,他本身是阻塞式的编程,所以时间都花费在了等待网页结果的返回和对爬取到的数据的写入上面.而如果采用非阻塞编程,那么就没有这个困扰.这边首先要理解一下阻塞和非阻塞的区别

python asyncio笔记

1.什么是coroutine coroutine,最早我是在lua里面看到的,coroutine最大的好处是可以保存堆栈,让程序得以继续执行,在python里面,一般是利用yield来实现,具体可以看如下文章: http://www.cnblogs.com/tqsummer/archive/2010/12/27/1917927.html python中的yield以及yield from语法可以让程序支持coroutine 2.asyncio库 Python3中,提供了基于coroutine的异

python asyncio 协程使用 (一)

由于脚本需要在完成事件处理后N秒检查事件处理结果,当执行失败时再执行另一个事件处理. 想要最小化完成这个功能.同时在第一时间就将执行完毕的结果反馈给接口. 因此想到使用协程. 使用之前先翻阅了一下现有的文档.以及参考了其他人的代码. 先改写成如下的用例: 1 import asyncio 2 3 async def do_some_work(x): 4 try: 5 return "success" 6 finally: 7 print('it can test') 8 await a

PYTHON ASYNCIO: FUTURE, TASK AND THE EVENT LOOP

from :http://masnun.com/2015/11/20/python-asyncio-future-task-and-the-event-loop.html Event Loop On any platform, when we want to do something asynchronously, it usually involves an event loop. An event loop is a loop that can register tasks to be ex

Python asyncio 模块

Python 3.4 asyncio是Python 3.4版本引入的标准库,直接内置了对异步IO的支持. asyncio的编程模型就是一个消息循环.我们从asyncio模块中直接获取一个EventLoop的引用,然后把需要执行的协程扔到EventLoop中执行,就实现了异步IO. 用asyncio实现Hello world代码如下: import asyncio @asyncio.coroutine def hello(): print("Hello world!") # 异步调用as

python asyncio

asyncio 是python3增加的特性.不过backport到了2.7了. python 2.7 Develop with asyncio Tasks and coroutines python 3.7 asyncio(org CN) REF: 一份详细的asyncio入门教程  有大量的例子 python中重要的模块--asyncio 不同线程的事件循环 很多时候,我们的事件循环用于注册协程,而有的协程需要动态的添加到事件循环中.一个简单的方式就是使用多线程.当前线程创建一个事件循环,然后

python asyncio学习截图

感觉对python越来越通了. 感觉不错, 截图 原文地址:https://www.cnblogs.com/aguncn/p/10156934.html

python asyncio 关闭task

import asyncio import time async def get_html(sleep_times): print("waiting") await asyncio.sleep(sleep_times) print("done after {}s".format(sleep_times)) if __name__ == "__main__": task1 = get_html(2) task2 = get_html(3) task