1

Function cant pass to next line because of asyncio.sleep. There is rest of the code but i will share just 3 lines. It explains everything. Console doesnt print 0 to console. If i move print(0) above of asyncio.sleep it prints to console.

async def getHistory(self): logging.info(f"Getting history for {self.parite}...") await asyncio.sleep(1) print(0) async def get_histories(): for parite in parite_list: asyncio.create_task(parite.getHistory()) asyncio.run(get_histories()) 
3
  • 1
    Of course it's blocking, that's the purpose of sleep. But after 1 second it continues, if the event loop is still running, which it isn't in your case. Commented Aug 10, 2021 at 15:02
  • @mkrieger1 after one second it is not continueing. that is the reason i asked here Commented Aug 10, 2021 at 15:10
  • The program ends as soon as the tasks are submitted to the loop, they're not finishing, just starting. You need to actually wait for them to finish to get the expected output. Commented Aug 10, 2021 at 19:22

1 Answer 1

2

It looks like you created the tasks but did not execute them. Try this with asyncio.gather:

import asyncio import logging async def getHistory(num): print(f"Getting history for {num}...") await asyncio.sleep(1) print(num) async def get_histories(): await asyncio.gather( asyncio.create_task(getHistory(1)), asyncio.create_task(getHistory(2)), asyncio.create_task(getHistory(3)) ) asyncio.run(get_histories()) 

Result:

% python asdf.py Getting history for 1... Getting history for 2... Getting history for 3... 1 2 3 
Sign up to request clarification or add additional context in comments.

2 Comments

If i move the print(0) to above of asyncio.sleep it prints. So asyncio.create_task calles the function. Anyway i will try your suggestion.
async def get_histories(): tasks = [] for parite in parite_list: tasks.append(asyncio.create_task(parite.getHistory())) await asyncio.gather(*tasks) asyncio.run(get_histories()) i did like this. But this time until sleep it work async but then rest of the function works non async. So strange.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.