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