Python asyncio
task 是协程和 Future 的桥梁。
迷心兔
我对你的感情大概就是,就算我们很久不说话,不聊天,或者哪天直接就没了任何联系,我还是会觉得你是我非常,非常重要的人...
展开
-
优雅地处理不同响应码的异步请求
urls.txt 文件https://regex101.com/https://docs.python.org/3/this-url-will-404.htmlhttps://www.nytimes.com/guides/https://www.mediamatters.org/https://1.1.1.1/https://www.politico.com/tipsheets/mo...转载 2019-12-16 20:52:48 · 378 阅读 · 5 评论 -
测试本地服务器的asyncio并发
1.搭建本地服务器from http.server import BaseHTTPRequestHandler, HTTPServerfrom socketserver import ThreadingMixInimport timeENCODING = 'utf-8'class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): ...转载 2019-11-16 14:03:15 · 237 阅读 · 0 评论 -
Asyncio Semaphore
import asyncioimport timeimport loggingimport nest_asyncionest_asyncio.apply() # 在jupyter需要这个,不然asyncio运行出错logging.basicConfig( # 用日志打印输出信息 level=logging.INFO, format="%(asctime)s %(pro...转载 2019-11-15 17:41:53 · 3873 阅读 · 0 评论 -
Asyncio Queue
import asyncioimport randomimport timeimport loggingimport nest_asyncionest_asyncio.apply() # 在jupyter需要这个,不然asyncio运行出错logging.basicConfig( # 用日志打印输出信息 level=logging.INFO, format="%(as...转载 2019-11-15 17:40:19 · 390 阅读 · 0 评论 -
Asyncio Losk
import asyncioimport timeimport loggingimport nest_asyncionest_asyncio.apply() # 在jupyter需要这个,不然asyncio运行出错logging.basicConfig( # 用日志打印输出信息 level=logging.INFO, format="%(asctime)s %(proc...转载 2019-11-15 17:38:51 · 89 阅读 · 0 评论 -
asyncio合并基础到动态协程
import timeimport asyncioimport loggingimport functoolsimport nest_asyncionest_asyncio.apply() # 需要这个,不然asyncio运行出错from threading import Threadlogging.basicConfig( # 用日志打印输出信息 level=logging...原创 2019-11-15 13:17:41 · 783 阅读 · 0 评论 -
asyncio常见编程方式
# 1.运行异步代码而不用担心循环"""import asyncioasync def main(): passasyncio.run(main())#如果你只有一个线程和进程,并且只有一个协程需要从头到尾运行"""# 2.在Python3.6 清理异步生成器之后的代码"""import asyncioasync def main(): pass...原创 2019-11-15 12:43:46 · 336 阅读 · 0 评论 -
【进程】创建一个新的循环实例
import asyncioimport osimport randomimport typingfrom multiprocessing import Processprocesses = []# 停止进程def cleanup(): global processes while processes: proc = processes.pop()...转载 2019-11-14 23:10:24 · 150 阅读 · 0 评论 -
【线程】创建一个新的循环实例
# import asyncio"""1.检查在调用函数时是否有循环运行2.返回其pid与当前进程pid匹配的运行循环(如果有)3.如果没有,获取存储在asyncio module中的全局变量中的线程全局LoopPolicy实例4.如果没有设置它,则使用锁用DefaultLoopPolicy实例化它。(_init_event_loop_policy方法)5.注意,DefaultLoo...转载 2019-11-14 22:56:23 · 177 阅读 · 0 评论 -
python aiomysql实例
代码重复太多,还要自己写sql语句的实例增删该查还有点用处吧# coding=utf-8import asyncioimport aiomysqlclass P_Mysql: def __init__(self, host, port, user, password, db): self.host = host self.port = por...原创 2019-10-12 16:45:10 · 357 阅读 · 0 评论 -
asyncio aiohttp lxml 网页爬虫实例
原因:查看asyncio ,aiohttp 和lxml配合的速度# coding=utf-8import asyncioimport loggingimport timefrom aiohttp import ClientSessionfrom lxml import etreelogging.basicConfig( level = logging.INFO, f...原创 2019-10-13 22:16:33 · 490 阅读 · 0 评论 -
asyncio 爬虫实例,只返回源码
# coding=utf-8import asyncioimport functoolsimport loggingimport timefrom concurrent.futures import ThreadPoolExecutorfrom aiohttp import ClientSessionlogging.basicConfig( level=logging.IN...原创 2019-10-11 21:45:39 · 163 阅读 · 0 评论 -
asyncio的as_completed和socket ——》收集http响应实例
原因:as_completed:逐个返回结果# asyncio 没有提供http协议的接口import timeimport asynciofrom urllib.parse import urlparse# 改成使用协程async def get_url (url): all_lines = [] # 通过socket请求html------------...转载 2019-10-10 10:55:02 · 378 阅读 · 0 评论 -
asyncio run_in_executor与线程池配合
# 使用多线程:在协程中集成阻塞ioimport asynciofrom concurrent.futures import ThreadPoolExecutorimport socketfrom urllib.parse import urlparsedef get_url(url): # 通过socket请求html url = urlparse(url) ...转载 2019-10-09 23:39:21 · 7766 阅读 · 4 评论 -
asyncio 有无ThreadPoolExecutor配合实例
1.协程和线程池结果中会认为配合线程池,不那么快。但是,配合还是会带来一些好处,比如:使用多线程,以至于整个主线程不阻塞# coding=utf-8import asyncioimport loggingfrom concurrent.futures import ThreadPoolExecutorimport timelogging.basicConfig( lev...转载 2019-10-09 21:29:22 · 1074 阅读 · 0 评论 -
asyncio cancel取消协程
# coding=utf-8import asyncioimport time# 协程中是不能使用同步阻塞编程的async def get_html (url): print('start get url', url) await asyncio.sleep(2) print('end get url')async def get_html2 (url)...转载 2019-10-09 20:57:42 · 1708 阅读 · 0 评论 -
asyncio run_until_complete和run_forever运行对比
原因:run_until_complete和run_forever运行对比,run_until_complete 来运行 loop ,等到 future 完成,run_until_complete 也就返回了。run_forever 会一直运行,直到 stop 被调用第一种运行方式# coding=utf-8import asyncioimport functoolsimport l...转载 2019-10-08 17:51:55 · 19632 阅读 · 5 评论 -
asyncio 将阻塞操作定义为——》可调出协程
原因:在协成中,如果有一个操作阻塞了,会影响其他的一串协成组中的其他协成,我们可以把容易产生阻塞的协成定义为可调出协成# coding=utf-8import asyncioimport loggingimport timelogging.basicConfig( level=logging.INFO, format="%(asctime)s [*] %(process...转载 2019-10-08 19:35:37 · 141 阅读 · 0 评论 -
asynncio 配合多进程
# coding=utf-8import asyncioimport timefrom multiprocessing import Processimport logginglogging.basicConfig( level=logging.INFO, format="%(asctime)s [*] %(process)d %(processName)s %(me...转载 2019-10-08 21:20:13 · 333 阅读 · 0 评论 -
asyncio call_at,call_soon和call_later用法
# coding=utf-8import asyncioimport functoolsimport logginglogging.basicConfig( level=logging.INFO, format="%(asctime)s [*] %(process)d %(processName)s %(message)s")def callback01 (ar...转载 2019-10-08 22:45:26 · 1472 阅读 · 0 评论 -
asyncio gather和wait并发方式
# coding=utf-8import asyncioimport timeasync def step1 (n, start): try: await asyncio.sleep(n) print("第一阶段完成") print("此时用时", time.time() - start) return n ...转载 2019-10-08 23:12:55 · 9322 阅读 · 2 评论 -
asyncio as_completed(逐个返回结果)实例
# coding=utf-8import asyncioimport timeasync def foo (n): print('Waiting: ', n) await asyncio.sleep(n) return nasync def main (): # 三个协程 coroutine1 = foo(1) coroutine2 ...转载 2019-10-08 23:29:56 · 2125 阅读 · 0 评论 -
asyncio和异步请求库aiohttp ——》多链接异步访问实例
原因:多链接异步访问# coding=utf-8import timeimport asynciofrom aiohttp import ClientSessionurl = "https://docs.python.org/3/library/asyncio-task.html"async def hello (url): async with ClientSessio...转载 2019-10-08 23:51:30 · 236 阅读 · 0 评论 -
asyncio的gather和aiohttp ——》收集http响应实例
# coding=utf-8import timeimport asynciofrom aiohttp import ClientSessionasync def hello (url): async with ClientSession() as session: async with session.get(url) as response: ...转载 2019-10-09 00:26:05 · 615 阅读 · 0 评论 -
asyncio的Semaphore 和 aiohttp 限制并发数量实例
# coding=utf-8import timeimport asynciofrom aiohttp import ClientSessionurl = "https://docs.python.org/3/library/asyncio-task.html"async def hello (url, semaphore): async with semaphore: ...转载 2019-10-09 00:40:26 · 5837 阅读 · 2 评论 -
asyncio Event(事件)
# coding=utf-8import asyncioimport functoolsdef set_event (event): print('在回调中设置事件') event.set()async def test (name, event): print('\t{} waiting for event'.format(name)) await...转载 2019-10-09 13:24:42 · 1638 阅读 · 0 评论 -
asyncio 队列(Queue)
# coding=utf-8import asyncioimport randomimport aiohttpNUMBERS = random.sample(range(100), 7)URL = 'http://httpbin.org/get?a={}'semaphore = asyncio.Semaphore(3)async def fetch_async (a): ...转载 2019-10-09 14:07:03 · 2167 阅读 · 0 评论 -
asyncio 尽量减少函数之间的明确依赖
1.第一种方式# coding=utf-8import loggingimport timeimport asynciologging.basicConfig( level=logging.INFO, format="%(asctime)s [*] %(message)s")async def hello1 (): logging.info(f"你好0...转载 2019-10-09 18:25:36 · 79 阅读 · 0 评论 -
asyncio 简单异步访问网页
原因:await asyncio.sleep(1) # 异步阻塞(等待另一个协程)task = event_loop.create_task(task_func()) # 在全局轮训器加入协成,只有加入全局轮训器才能被监督执task.add_done_callback(callback) # 添加一个回调event_loop = asyncio.get_event_loop() # 获...转载 2019-10-08 16:52:57 · 353 阅读 · 0 评论