Open In App

How to Fix – Timeouterror() from exc TimeoutError in Python

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

We can prevent our program from getting stalled indefinitely and gracefully handle it by setting timeouts for external operations or long-running computations. Timeouts help in managing the execution of tasks and ensuring that our program remains responsive. In this article, we will see how to catch Timeouterror() from exc TimeoutError in Python.

What is Timeouterror() from exc TimeoutError in Python?

In Python’s asyncio tasks, a timeout error is raised when an operation takes longer than the allotted time to finish. This error is raised to show that the job was not completed in the allotted amount of time. It is often used in asynchronous programming to deal with tasks that take too long to finish. Developers can catch this problem and use the right way to deal with it or try again to manage timeouts well in their asyncio programs.

Error Syntax

TimeoutError() from exc TimeoutError

below, are the reasons for the occurrence of Python TimeoutError() from exc TimeoutError in Python:

  • Slow Operations
  • Infinite Loops

Slow Operations

In below code the fetch_data function pretends to wait for a slow internet connection by pausing for 2 seconds. In main, a timeout of 1 second is set using asyncio.TimeoutError. When asyncio.wait_for waits for fetch_data to finish, it takes too long, so it gives a TimeoutError.

Python3
import asyncio

async def my_task():
    await asyncio.sleep(3)  # Simulate some long-running operation
    return "Task completed"

async def main():
    result = await asyncio.wait_for(my_task(), timeout=2)
    print(result)

asyncio.run(main())


Output:

 File "<main.py>", line 8, in main
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 502, in wait_for
raise exceptions.TimeoutError() from exc TimeoutError

Infinite Loops

In below code the Infinite_loop is a function that keeps running forever. In main, a timeout of 2 seconds is set, but because the loop never ends, it takes too long, resulting in a TimeoutError.

Python3
import asyncio

async def my_task():
    while True:
        await asyncio.sleep(1)  # Infinite loop, simulating ongoing task

async def main():
    await asyncio.wait_for(my_task(), timeout=2)

asyncio.run(main())

Output:

File "<main.py>", line 8, in main
File "/usr/local/lib/python3.11/asyncio/tasks.py", line 502, in wait_for
raise exceptions.TimeoutError() from exc TimeoutError

Solution for Timeouterror() from exc TimeoutError in Python

Below, are the approaches to solve Python “Timeouterror() from exc TimeoutError” in Python:

Using asyncio.timeout()

Below, code defines an asynchronous task that pauses for 5 seconds and a main coroutine that waits for it to complete within 2 seconds, printing success if completed or a timeout message if not. Then, it executes the main coroutine using asyncio.run().

Python3
import asyncio

async def long_running_task():
    await asyncio.sleep(5)

async def main():
    try:
        await asyncio.wait_for(long_running_task(), timeout=2)
        print("Task completed successfully.")
    except asyncio.TimeoutError:
        print("The task took too long and timed out.")

asyncio.run(main())

Output
The task took too long and timed out.

Using asyncio.wait_for()

Below, code defines an asynchronous task that pauses for 5 seconds and a main coroutine that waits for it to complete within 2 seconds. It prints the result if completed or a timeout message if not. Finally, it executes the main coroutine using asyncio.run().

Python3
import asyncio

async def long_running_task():
    await asyncio.sleep(5)  

async def main():
    try:
        result = await asyncio.wait_for(long_running_task(), timeout=2)
        print("Task completed:", result)
    except asyncio.TimeoutError:
        print("Task timed out!")

asyncio.run(main())

Output
Task timed out!


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads