Home >Backend Development >Python Tutorial >How Can I Prevent Indefinitely Halting Python Functions with a Timeout?

How Can I Prevent Indefinitely Halting Python Functions with a Timeout?

DDD
DDDOriginal
2024-12-24 00:55:09968browse

How Can I Prevent Indefinitely Halting Python Functions with a Timeout?

Timeout on Function Calls

When invoking a function in Python that may halt the script's execution indefinitely, it becomes necessary to establish a mechanism to prevent it. The solution lies in setting a timeout threshold after which the script will intervene and terminate the function.

Using the Signal Package

For UNIX-based systems, the signal package offers a robust solution. To utilize it:

  1. Import the signal package: import signal
  2. Define a handler function to be invoked upon timeout. This function should raise an exception to terminate the process.
  3. Use the signal.alarm() function to specify the timeout duration.
  4. Set the SIGALRM signal handler using signal.signal(signal.SIGALRM, handler).
  5. Call the potentially stalling function within a try block. In the event of a timeout, the handler exception will be raised.
  6. If desired, cancel the timer using signal.alarm(0) once the function has completed within the allotted time.

Here is an illustrative example:

import signal

# Handler function
def handler(signum, frame):
    print("Timeout reached!")
    raise Exception("Timeout exception")

# Function that may stall indefinitely
def loop_forever():
    while True:
        print("Looping")
        # Pause execution for 1 second
        time.sleep(1)

# Set timeout to 5 seconds
signal.alarm(5)
signal.signal(signal.SIGALRM, handler)

try:
    loop_forever()
except Exception as exc:
    print("Exception:", exc)

If the function loop_forever() fails to complete within 5 seconds, the handler function will be invoked, raising the timeout exception and terminating the process.

The above is the detailed content of How Can I Prevent Indefinitely Halting Python Functions with a Timeout?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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