【问题标题】:Alternative to asyncio.wait?asyncio.wait 的替代方案?
【发布时间】:2021-02-03 14:40:50
【问题描述】:

我收到此错误:

D:\pythonstuff\demo.py:28: DeprecationWarning: 自 Python 3.8 起不推荐将协程对象显式传递给 asyncio.wait(),并计划在 Python 3.11 中删除。 等待 asyncio.wait([

等了 1 秒!
等了 5 秒!
经过的时间:0小时:0分钟:5秒

进程以退出代码 0 结束

当我运行code:

import asyncio
import time

class class1():
    async def function_inside_class(self):
        await asyncio.sleep(1)
        print("Waited 1 second!")

    async def function_inside_class2(self):
        await asyncio.sleep(5)
        print("Waited 5 second!")

def tic():
    global _start_time
    _start_time = time.time()

def tac():
    t_sec = round(time.time() - _start_time)
    (t_min, t_sec) = divmod(t_sec,60)
    (t_hour,t_min) = divmod(t_min,60)
    print('Time passed: {}hour:{}min:{}sec'.format(t_hour,t_min,t_sec))

object = class1()


async def main():
    tic()
    await asyncio.wait([
        object.function_inside_class(),
        object.function_inside_class2()
        ])
    tac()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close()

asyncio.wait 有什么好的替代品吗?我不希望每次启动应用程序时都在控制台中出现警告。

编辑:我不想只是隐藏错误,这是不好的做法,我正在寻找其他方法来做相同或类似的事情,而不是另一个异步库来恢复旧功能。

【问题讨论】:

  • 你不能只修复用法吗? IIRC,文档解释了这种弃用。
  • 我不希望每次启动应用程序时都在控制台中显示警告您可以随时隐藏它们(请参阅here
  • 如果某些东西被弃用,这通常是有充分理由的,仅仅隐藏错误并不是一个好习惯。如果我隐藏此错误,我的应用程序也不会非常向前兼容,因为它已在 3.11 中被完全删除

标签: python python-3.x asynchronous python-asyncio python-3.8


【解决方案1】:

您可以按照文档here 中的建议这样称呼它

文档中的示例:

async def foo():
    return 42

task = asyncio.create_task(foo())
done, pending = await asyncio.wait({task})

所以你的代码会变成:

await asyncio.wait([
    asyncio.create_task(object.function_inside_class()),
    asyncio.create_task(object.function_inside_class2())
    ])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-06-13
    • 2015-03-03
    • 2015-09-25
    • 2019-12-16
    • 2011-06-20
    • 2015-11-03
    • 2014-04-03
    • 2011-12-13
    相关资源
    最近更新 更多