Home > Backend Development > Python Tutorial > How to Handle Function Timeouts in Python?

How to Handle Function Timeouts in Python?

Susan Sarandon
Release: 2024-12-24 10:13:45
Original
296 people have browsed it

How to Handle Function Timeouts in Python?

Handling Function Timeouts in Python

When calling a function that may potentially stall, it becomes crucial to have a mechanism in place to gracefully handle such situations and prevent the script from freezing indefinitely. One effective solution to this problem is to set a timeout for the function call.

The Python signal module provides the necessary functionality to register a signal handler that will be invoked if the function exceeds the specified timeout. Here's how it can be implemented:

import signal

def handler(signum, frame):
    print("Timeout reached!")
    raise Exception("Function call timed out")

def function_to_timeout():
    print("Running function...")
    # Simulate a long-running task
    for i in range(10):
        time.sleep(1)

# Register the signal handler
signal.signal(signal.SIGALRM, handler)

# Set a timeout of 5 seconds
signal.alarm(5)

try:
    # Call the function
    function_to_timeout()
except Exception as exc:
    print(exc)
Copy after login

When the function_to_timeout() is called, it will print a message indicating that it is running. The signal.alarm(5) sets a 5-second timeout, after which the handler function will be triggered. Within the handler, an exception is raised to terminate the function call.

This approach allows you to set a specific timeout for the function and gracefully exit the script in case the function takes longer than the specified time.

The above is the detailed content of How to Handle Function Timeouts in Python?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template