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...

4
  • 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. Commented Oct 16, 2022 at 7:31
  • Because B() is actually called by both async and non-async functions Commented Oct 16, 2022 at 15:27
  • stackoverflow.com/questions/70231451/…. 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(). Commented Oct 17, 2022 at 22:59
  • Does B actually need to access the result or just return it? Commented Oct 18, 2022 at 14:18

1 Answer 1

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())
Sign up to request clarification or add additional context in comments.

3 Comments

No I can't, I get the error "RuntimeError: This event loop is already running". Since asyncio doesn't support nested loop
@graille Is it necessary to be in the current running loop? What if you could run it in a new event loop?
You cannot launch a new loop when a loop is already running: "RuntimeError: Cannot run the event loop while another loop is running"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.