There is a socket related function call in my code, that function is from another module thus out of my control, the problem is that it blocks for hours occasionally, which is totally unacceptable, How can I limit the function execution time from my code? I guess the solution must utilize another thread.
You can limit the execution time of a function by using the signal library.
You can use the time. time() function. It returns the time since Jan 1st 1970 in seconds! So, you can just do this : import time b = True #declare boolean so that code can be executed only if it is still True t1 = time.
To stop code execution in python first, we have to import the sys object, and then we can call the exit() function to stop the program from running. It is the most reliable way for stopping code execution. We can also pass the string to the Python exit() method.
Using return is the easiest way to exit a function. You can use return by itself or even return a value.
An improvement on @rik.the.vik's answer would be to use the with
statement to give the timeout function some syntactic sugar:
import signal from contextlib import contextmanager class TimeoutException(Exception): pass @contextmanager def time_limit(seconds): def signal_handler(signum, frame): raise TimeoutException("Timed out!") signal.signal(signal.SIGALRM, signal_handler) signal.alarm(seconds) try: yield finally: signal.alarm(0) try: with time_limit(10): long_function_call() except TimeoutException as e: print("Timed out!")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With