繁体   English   中英

如何使异步代码在启动时运行 - Python

[英]How to make async code run on startup - Python

嘿,我如何让我的async代码在启动时运行?

所以这是我能想到的最简单的例子。

async def mainMenuCLI():
  print("This is the CLI")

而且我希望异步mainMenuCLI在启动时运行,但我不希望它执行太多任务,因为我不确定最大值是多少:(

我需要它是异步的,因为async_input , discord.py 和其他东西,只是不要告诉我让它同步,谢谢!

如果我理解你的问题......你需要这样的东西吗?

import asyncio


async def async_example():
    print("hellooooo, I'm an async function")
 


async def main():
    asyncio.Task(async_example())  


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

如果需要,您可以在异步函数之外添加一些任务:

import asyncio


async def async_example():
    print("hellooooo, I'm an async function")
    await asyncio.sleep(1)
    print("async function done")


async def main():
    asyncio.Task(async_example())  

    print('This is before wait')
    await asyncio.sleep(1)
    print('This is after await')
    await asyncio.sleep(1)
    print('Ok, goodbye')

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

*注意:如果您的 py 版本低于 3.7, 请根据 asyncio.ensure_future 更改 asyncio.Task

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM