Home > Mobile >  How to call async function within non async function in python?
How to call async function within non async function in python?

Time:09-29

I know about await and async must be pair. But. here is my problem:

I hava a function like

def url_open(req):
    #fetch url content synchronize

and now, I want to change to another version like:

def url_open(req):
    await self.websocket.send(req)
    content = await self.websocket.recv()

the problem is url_open function was exist in many place in the whole project, and it 'is in the bottom of the call tree. it's not possible to make all the caller to be async function.

So, how can I make this work? get some result from another async functions like in python websocket module?

======= updated ======

After I tried as @Viliam Popovec provided I got this warning

RuntimeWarning: coroutine 'hello' was never awaited

and error

This event loop is already running

The websocket was run like this in my app

async def main():
    async with websockets.serve(echo, '0.0.0.0', 8001):
        await asyncio.Future()

asyncio.run(main())

It't seems that the new event loop has conflicts with the existing websocket runloop

CodePudding user response:

If you can't modify all instances of url_open function to be ansynchronous, then you could use loops to call some async function (e.g. hello() in code sample below).

async def hello():
    await asyncio.sleep(1)
    print("Hello World!")


def url_open():
    loop = asyncio.get_event_loop()
    loop.run_until_complete(hello())
  • Related