Code: Select all
import asyncio
import asyncio.exceptions
async def worker(semaphore, task_id):
async with semaphore:
try:
if task_id == 2:
raise ValueError("Something went wrong in task 2")
await asyncio.sleep(1)
print(f"Task {task_id} completed")
return f"Result from task {task_id}"
except ValueError as e:
print(f"Task {task_id} caught exception: {e}")
return None #
async def main():
semaphore = asyncio.Semaphore(2)
tasks = [worker(semaphore, i) for i in range(4)]
results = await asyncio.gather(*tasks, return_exceptions=True)
for i, result in enumerate(results):
if isinstance(result, Exception):
print(f"Task {i} raised an exception {result}")
else:
print(f"Task {i} returned {result}")
if __name__ == "__main__":
asyncio.run(main())
< /code>
Bearbeiten: Wiederholende Versuche verursachten auch < /p>
RuntimeError: asyncio.run() cannot be called from a running event loop