Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass an async function to a thread target in Python?

I have the following code:

async some_callback(args):
    await some_function()

and I need to give it to a Thread as a target:

_thread = threading.Thread(target=some_callback, args=("some text"))
_thread.start()

The error that I get is "some_callback is never awaited".
Any ideas how can I solve this problem?

like image 701
Damian-Teodor Beleș Avatar asked Jan 08 '20 11:01

Damian-Teodor Beleș


Video Answer


1 Answers

You can do it by adding function between to execute async:

async def some_callback(args):
    await some_function()

def between_callback(args):
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)

    loop.run_until_complete(some_callback(args))
    loop.close()

_thread = threading.Thread(target=between_callback, args=("some text"))
_thread.start()

like image 62
norbeq Avatar answered Sep 19 '22 01:09

norbeq