0

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.

1
  • The deprecation warning is a new "fearure" in 3.10, read here: docs.python.org/3/library/… Commented Nov 22, 2021 at 15:00

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks for your quick replies! I'm now getting: RuntimeError: Task <Task pending name='Task-1' coro=<main() running at <remoed_path>/main.py:22> cb=[_run_until_complete_cb() at>/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/base_events.py:184]> got Future <Future pending cb=[_chain_future.<locals>._call_check_cancel() at /Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/asyncio/futures.py:384]> attached to a different loop
The answer is correct IMO. There must be another issue responsible for the RuntimeError
Yes, I'm sure there must be.
Issue probably is, once you call asyncio.run(main()) once, you've started an event loop that doesn't necessarily (in my experience) go away with a fresh execution. Maybe that is a result of my environment being crap or something. Therefore (as I often experienced) that second execution is looking to start a further run of main() in a further loop, hence the warning.
Hmmmm. Just reading up and the newer methods should clean up after themselves. Is the class/.py "stream" something forked off "Streams"?
|
1

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())

4 Comments

As you wrote this is copied from somewhere and it addresses a different issue than it was asked.
So in your opinion it doesn't (i) detect (and handle) when there actually is "no running event loop" and (ii) doesn't start a event new loop if there is "no running event loop"? That is an interesting take on addressing a different issue than was asked.
If you are are starting the event loop as the first thing after the program start, then you don't need to test wether it isn't running already.
Unfortunately, if I try that, I frequently get told there is an event loop already running. Whether windows isn't cleaning itself up right or not I don't know. Either way, I need the above to run what I want to.
0

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!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.