V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
bestehen
V2EX  ›  Python

Python 异步 asyncio

  •  
  •   bestehen · 2018-07-26 11:28:18 +08:00 · 2720 次点击
    这是一个创建于 2099 天前的主题,其中的信息可能已经有所发展或是发生改变。

    tasks = [fetch(BASE_URL + page_url, callback=parse_body, title=title) for title, page_url in TITLE2URL.items()] loop.run_until_complete(asyncio.gather(*tasks[:500])) 这里是把 500 个事件注册到事件循环? 那 j 假如我有 2000 个呢?

    还有

    tasks = [asyncio.ensure_future(task(i)) for i in range(0,300)] loop.run_until_complete(asyncio.gather(*tasks))

    tasks = [task(i) for i in range(0,300)] loop.run_until_complete(asyncio.wait(tasks))

    这两个区别是啥

    6 条回复    2018-07-26 17:03:16 +08:00
    KeatingSmith
        1
    KeatingSmith  
       2018-07-26 13:50:53 +08:00   ❤️ 1
    run_unitl_complete() 需要传入一个 Future 对象,但传入的是一个协程的话,会自动封装成 Future 对象。

    asycio.wait() 和 asyncio.gather() 两个函数都是协程并行时需要用的,本质上没有区别。

    asyncio.wait() 参数类型是列表 List[async],asyncio.gather() 则是多个协程 (async_1, async_2, ... async_n)

    一般来说,使用协程有时候会有回调。

    asyncio.wait() 获取运行结果:

    dones, pendings = await asyncio.wati(tasks)

    asyncio.gather() 获取运行结果:

    results = await asysncio.gather(*tasks)
    KeatingSmith
        2
    KeatingSmith  
       2018-07-26 13:52:17 +08:00
    asyncio.wait() 和 asyncio.gather() 接收多个协程,本身自己返回一个协程对象。
    KeatingSmith
        3
    KeatingSmith  
       2018-07-26 13:58:53 +08:00
    ensure_future() 只是把协程封装成 task, task 是 Future 的子类。
    enenaaa
        4
    enenaaa  
       2018-07-26 14:08:20 +08:00
    python 的协程一直搞不懂
    zhzer
        5
    zhzer  
       2018-07-26 16:14:17 +08:00
    Future 是独立于协程的,用于并行时处理协程对象的结果; Task 是事件循环的基本单位
    gather 一般用来解决多协程 callback 问题,当所有协程结束,这个协程才会结束(并 callback ),等于打包成主协程

    没理解错的话,你代码里的 task 只是协程对象,并非 Task 对象
    当然使用 py 协程不用理解太多,烧脑,直接把协程丢给 run_until_complete,它会处理好封装问题。
    并且 py 基于协程的库,正常使用,只需要 async 和 await 就能跑起来了
    cosven
        6
    cosven  
       2018-07-26 17:03:16 +08:00
    asyncio gather 比较简单:它总是会等所有协程运行完毕。
    而 wait 支持设置一些参数:比如设置等待时间;它可以不等待所有协程都运行完。

    一个 wait 的使用常见场景:你开了 3 个协程,它们分别用不同方法去做同一件事,你只需要它们其中一个完成就可以了,这时,你可以使用 wait。

    我感觉你去看两个函数的文档应该就能搞清楚它们的区别。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1536 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 23:59 · PVG 07:59 · LAX 16:59 · JFK 19:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.