Home > database >  python: unable to understand how async works. not able to run the python script
python: unable to understand how async works. not able to run the python script

Time:12-28

I am using python 3.9

I wanted to check what happens when I call sync function inside async

I have test.py

import snoop

def get_chat_id(name):
    time.sleep(3)
    return "chat-%s" % name

async def main():
    result = get_chat_id("django")
    print(result)

if __name__ == "__main__":
    main()

When i try to run i get

$ python test.py
/home/user/test.py:13: RuntimeWarning: coroutine 'main' was never awaited                                                                                                                                    
  main()                                                                                                  
RuntimeWarning: Enable tracemalloc to get the object allocation traceback   

So then I tried putting await before main()

import snoop
import asyncio

def get_chat_id(name):
    time.sleep(3)
    return "chat-%s" % name

async def main():
    result = get_chat_id("django")
    print(result)

if __name__ == "__main__":
    await main()

When i run i get

$ python test.py
  File "/home/user/test.py", line 13                                                                                                                                                                         
    await main()                                         
    ^                                                                                                                                                                                                                  
SyntaxError: 'await' outside function  

So what is the correct way to make this script working

CodePudding user response:

Quoting from the documentation:

Note that simply calling a coroutine will not schedule it to be executed [...]

To actually run a coroutine, asyncio provides three main mechanisms:

  • The asyncio.run() function to run the top-level entry point “main()” function (see the above example.)

The given example is the following:

import asyncio

async def main():
    print('hello')
    await asyncio.sleep(1)
    print('world')

asyncio.run(main())

So your case would be:

import asyncio

async def get_chat_id(name):
    await asyncio.sleep(3)
    return "chat-%s" % name

async def main():
    result = await get_chat_id("django")
    print(result)

if __name__ == "__main__":
    asyncio.run(main())
  • Related