【问题标题】:python: Task got bad yield:蟒蛇:任务得到了不好的收益:
【发布时间】:2021-08-10 19:18:25
【问题描述】:

我的目标是向端点列表发出并行请求,因此使用 asyncio ensure_future 可以请看一下并告诉我如何修复错误(python3.6.7)

import asyncio
import treq


async def main_aysnc():
    loop = asyncio.get_event_loop()
    await start_coros_parllel()

async def start_coros_parllel():
    config = {}
    config['services'] = [ 
        b'https://www.google.com',
        b'https://www.yahoo.com',
        b'https://www.facebook.com'
        ]
    results = await asyncio.gather(*[asyncio.ensure_future(treq.get(service)) for service in config['services']])
    

if __name__ == "__main__":
    asyncio.get_event_loop().run_until_complete(main_aysnc())

日志

Traceback (most recent call last):
  File "2cr.py", line 35, in <module>
    asyncio.get_event_loop().run_until_complete(main_aysnc())
  File "/Users/vchauhan/.pyenv/versions/3.6.7/lib/python3.6/asyncio/base_events.py", line 473, in run_until_complete
    return future.result()
  File "2cr.py", line 7, in main_aysnc
    await start_coros_parllel()
  File "2cr.py", line 20, in start_coros_parllel
    results = await asyncio.gather(*[asyncio.ensure_future(treq.get(service)) for service in config['services']])
  File "/Users/vchauhan/.pyenv/versions/3.6.7/lib/python3.6/asyncio/tasks.py", line 537, in _wrap_awaitable
    return (yield from awaitable.__await__())
RuntimeError: Task got bad yield: <Deferred at 0x104cc5048>

【问题讨论】:

  • 有什么意见吗?
  • @ArtiomKozyrev 我最终使用 aiohttp 发出请求。谢谢。
  • 很高兴听到它!

标签: python-3.x python-asyncio twisted


【解决方案1】:

问题是您不应该将asynciotreq 一起使用。

根据文档:

treq 依赖于 Python 2.7 上最近的 Twisted 和函数 Python 3.3+(包括 PyPy)。

如果您想使用asyncio,您必须使用其他一些 http 客户端框架,例如aiohttp。

如果您需要任何关于如何使用 aiohttp 客户端的示例,请随时询问。

【讨论】:

    猜你喜欢
    • 2021-11-09
    • 2020-05-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-27
    • 1970-01-01
    • 1970-01-01
    • 2023-01-20
    • 1970-01-01
    相关资源
    最近更新 更多