简体   繁体   中英

How to call async function within non async function in python?

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

If you can't modify all instances of url_open function to be ansynchronous, then you could use loop s to call some async function ( eg 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())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM