0

I want to run an async python script that has a sync part that has an assync task again

Is it possible?

This is an minimal example:

import asyncio
import threading

async def do_async3():
    # Asynchronous task logic
    print("Async Task 3 started")
    await asyncio.sleep(2)  # Simulating asynchronous work
    print("Async Task 3 completed")

def do1():
    print("Task 1")

def do2():
    print("Task 2")

def do4():
    print("Task 4")

def do5():
    print("Task 5")

async def main():
    print("main")
    # Synchronous tasks
    do1()
    do2()

    # Asynchronous task
    await do_async3()

    # Synchronous tasks after async task
    do4()
    do5()

# Call asyncio.run(main()) from a synchronous context
def run_main_sync(loop):
    print("run_main_sync")
    asyncio.set_event_loop(loop)
    loop.run_until_complete(main())

# New asynchronous function that calls run_main_sync
async def run_main_async():
    print("start")
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    run_main_sync(loop)

# Run the asynchronous function
asyncio.run(run_main_async())

I want to execute the async task inside the do_async3 function get the result, do some sync tasks and wrap it in an other async task that is independent from the previous async task

But when I run the code I get the following:

(env) python proba.py
start
run_main_sync

Traceback (most recent call last): ... RuntimeError: Cannot run the event loop while another loop is running

sys:1: RuntimeWarning: coroutine 'main' was never awaited

1 Answer 1

0

Change you run_main_async to this

async def runner():
    await asyncio.gather(*[main()])
def run_main_async():
    asyncio.run(runner())

run_main_async()
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your response! @Артем Романюк But your code collect tasks from the main and it runs them through the runner and run_main_async. I want to execute the async task inside the do_async3 function get the result, do some sync tasks and wrap it in an other async task that is independent from the previous async task

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.