New to asyncio: how to run tasks in an enviroment where an event loop already exists

As stated in the title, how can I test and run asyncio tasks in an envrioment where an event loop already exists, e.g. in Spyder?

I tried the suggested nest-asyncio · PyPI package on the web, but it seems not to work for me.

I tried this pattern too, unsuccesfully (syntax error “yield outside function” when I run await main())

async def something():
    await some_async_work()

async def main():
   await something()

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

Am I missing something?

This part, at least, has nothing to do with Spyder, and is just as easily reproduced at the REPL.
Calling main creates a coroutine object, which needs to be “run” within an event loop - it can’t just be awaited at top level.

asyncio.get_event_loop should give you an appropriate main event loop - which, when using Spyder to test the code, should be (to my understanding) the one that it already set up.

Try:

import asyncio

async def something():
    await some_async_work()

async def main():
   await something()

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

I’m learning asyncio these days though the Python documentation and its high-level API which aims not to bother with the loop event itself. All the examples are initiated through the call as in asyncio.run(main()). This results in an error in Spyder and other enviroment which I wish to resolve. The error is This event loop is already running and also your solution gives me this error. I don’t know if I am missing something. Does your snippet works in a enviroment where an “event loop” is already set-up?

Side note: The asyncio REPL can handle top-level await. It’s just the regular REPL, which doesn’t have an event loop, that can’t.

I still have not found a solution to my problem, to date I am learning asyncio by running the Python interpreter from a terminal and not from an coding enviroment with an already set-up event loop. If someone has a solution, I will gladly try it, thanks.

Do you run this:

python3

Or this:

python3 -m asyncio

? The second one gives you a REPL with an event loop.

I run my script main.py as python.exe -i main.py on Windows

Ah, so you only have the basic REPL, not an asyncio-aware one. I’d recommend trying out python.exe -m asyncio and then importing your script, to see how that works for you.

With the “basic REPL” it does work though, I do not have a problem when running the Python interpreter from a new terminal. The problem is when I launch my script in a enviroment as Spyder (which I would like to use). Does your suggestion still apply to me?