简体   繁体   中英

How to make async code run on startup - Python

Heyy, how would I make my async hronous code run on startup?

So this is the easiest example I could think of to make.

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

And I want the asynchronous mainMenuCLI to run on startup but I don't want it to take as many tasks because I'm not sure what is the max:(

I need it to be async because of async_input , discord.py and stuff, just don't tell me to make it sync, thanks!

If I understand your question... Do you need something likethis?

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())

You can add some tasks outside the async func if you need:

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())

*Note: if your py version is prior to 3.7, change asyncio.Task per asyncio.ensure_future .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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