Skip to content
Advertisement

async exec in python

I’d like to call exec in an async function and do something like the following code (which is not valid):

import asyncio

async def f():
    await exec('x = 1n' 'await asyncio.sleep(x)')

More precisely, I’d like to be able to wait for a future inside the code that runs in exec.

How can this be achieved?

Advertisement

Answer

Note: F-strings are only supported in python 3.6+. For older versions, use %s, .format() or the classic + concatenation.

async def aexec(code):
    # Make an async function with the code and `exec` it
    exec(
        f'async def __ex(): ' +
        ''.join(f'n {l}' for l in code.split('n'))
    )

    # Get `__ex` from local variables, call it and return the result
    return await locals()['__ex']()

Known issues:

  • If you use new lines in a string (triple quotes), it will mess up the formatting.
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement