Issue
I'm attempting to learn how to run asynchronous code in google co-labs with asyncio. However, I am having issues returning the results.
An example I set up for myself looks like this:
async def main():
task = asyncio.create_task(other_function())
print("1")
await asyncio.sleep(1)
print("2")
await task
async def other_function():
print('A')
await asyncio.sleep(1)
print('B')
asyncio.run(main())
This results in the error "asyncio.run() cannot be called from a running event loop"
I determined that because of the way google co-labs runs its event loops, asyncio.run() was not necessary and attempted to re-run the code with this part removed.
However, by changing the bottom line to just main() instead of asyncio.run(main()) the output is "<coroutine object main at 0x79c6076fa500>". Which is not what I'm looking for.
In theory the output should be
1
A
2
B
As of yet, I have been unable to find a solution. Any help or pointers in the right direction would be greatly appreciated.
Solution
In google-colab, just put await main()
at the end:
import asyncio
async def main():
task = asyncio.create_task(other_function())
print("1")
await asyncio.sleep(1)
print("2")
await task
async def other_function():
print('A')
await asyncio.sleep(1)
print('B')
await main()
Output:
1
A
2
B
Answered By - Andrej Kesely
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.