0

I have this configuration

async def A():
    B()

async def C():
    # do stuff

def B():
    # do stuff
    r = C()
    # want to call C() with the same loop and store the result

asyncio.run(A())

I don't really know how to do that. I tried this by reading some solutions on the web:

def B():
    task = asyncio.create_task(C())
    asyncio.wait_for(task, timeout=30)
    result = task.result()

But it doesn't seem to work...

graille
  • 1,131
  • 2
  • 14
  • 33
  • Why do not make the `B` async and `await` it in `A`? In that case, you could be able to invoke `r = await C()` in `B`. – Artyom Vancyan Oct 16 '22 at 07:31
  • Because B() is actually called by both async and non-async functions – graille Oct 16 '22 at 15:27
  • https://stackoverflow.com/questions/70231451/wrapping-python-async-for-synchronous-execution/70254610#70254610. The idea is to start a second thread that runs the coroutine C() and returns the result. Then instead of simply calling C() in your function B(), you do `r = asyncio.run_coroutine_threadsafe(C(), loop).result()`. – Paul Cornelius Oct 17 '22 at 22:59
  • Does `B` actually need to *access* the result or just return it? – MisterMiyagi Oct 18 '22 at 14:18

1 Answers1

0

Since asyncio does not allow its event loop to be nested, you can use nest_async library to allow nested use of asyncio.run and asyncio.run_until_complete methods in the current event loop or a new one:

First, install the library:

pip install nest-asyncio

Then, add the following to the beginning of your script:

import nest_asyncio

nest_asyncio.apply()

And the rest of the code:

async def A():
    B()

async def C():
    # do stuff

def B():
    # do stuff
    loop = asyncio.get_event_loop()
    result = loop.run_until_complete(C())
    # want to call C() with the same loop and store the result

asyncio.run(A())
msamsami
  • 644
  • 5
  • 10
  • No I can't, I get the error "RuntimeError: This event loop is already running". Since asyncio doesn't support nested loop – graille Oct 16 '22 at 03:20
  • @graille Is it necessary to be in the current running loop? What if you could run it in a new event loop? – msamsami Oct 16 '22 at 03:30
  • You cannot launch a new loop when a loop is already running: "RuntimeError: Cannot run the event loop while another loop is running" – graille Oct 16 '22 at 15:31
  • @graille edited the answer. It should work now! – msamsami Oct 17 '22 at 06:17