JazzHands
JazzHands

Reputation: 73

Python asyncio not executing

I'm not really a Python expert, so excuse me if this is really obvious. I'm trying to run a script using asyncio. Relevant bits of code:

import websockets
import asyncio

stream = websockets.connect(<resource_uri>)

async def main():
    async with stream as receiver:
        while True:
            data = receiver.recv()
            # do stuff


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

When I run this, I get:

DeprecationWarning: There is no current event loop loop = asyncio.get_event_loop()

Similarly, using

''' loop = asyncio.get_running_loop() '''

instead, I get

RuntimeError: no running event loop.

Any ideas? I guess it's something to do with main() not running in the correct thread...

I'm using Python 3.10.

Upvotes: 0

Views: 3044

Answers (3)

JazzHands
JazzHands

Reputation: 73

It seems there's an issue with websockets and Python 3.10. Looks like I'll have to find a workaround. Thanks for your time!

Upvotes: 0

jsbueno
jsbueno

Reputation: 110261

Newer code should use just asyncio.run(main()) - that will automatically create a new instance loop and "run until complete" on the awaitable.

Upvotes: 2

Amiga500
Amiga500

Reputation: 1275

Try this, works for me on 3.8 (and probably originally got from someone smarter than me that posted it on here!!)

 try:
    loop = asyncio.get_running_loop()
 except RuntimeError:  # 'RuntimeError: There is no current event loop...'
    loop = None

 if loop and loop.is_running():
     print('Async event loop already running. Adding coroutine to the event loop.')
     tsk = loop.create_task(main())
     # ^-- https://docs.python.org/3/library/asyncio-task.html#task-object
     # Optionally, a callback function can be executed when the coroutine completes
     tsk.add_done_callback(
        lambda t: print(f'Task done with result = {t.result()}'))
 else:
    print('Starting new event loop')
    asyncio.run(main())

Upvotes: 1

Related Questions