Search code examples
pythonpython-multithreadingpython-asyncio

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!


Solution

  • Since Python 3.7 there is asyncio.run.

    Replace

        Thread(target=func1).start()
    

    by

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