简体   繁体   中英

Python async and sync functions executed as threads

I would like to call an async function from a pure sync code. I would like to execute that async function in the background without stucking my prog. My idea is to use the threading module.

from threading import Thread
import asyncio

async def func1():
    ...

def func2():
    ...

if __name__ == '__main__':
    Thread(target=func1).start()
    Thread(target=func2).start()

Any idea? Thanks in advance!

Since Python 3.7 there isasyncio.run .

Replace

    Thread(target=func1).start()

by

    Thread(target=asyncio.run, args=(func1(),)).start()

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