This question already has an answer here:
- Timeout on a function call 13 answers
I have a shell script that loops through a text file containing URL:s that I want to visit and take screenshots of.
All this is done and simple. The script initializes a class that when run creates a screenshot of each site in the list. Some sites take a very, very long time to load, and some might not be loaded at all. So I want to wrap the screengrabber-function in a timeout script, making the function return False
if it couldn't finish within 10 seconds.
I'm content with the simplest solution possible, maybe setting a asynchronous timer that will return False after 10 seconds no matter what actually happens inside the function?
I rewrote David's answer using the
with
statement, it allows you do do this:Which will raise a TimeoutError.
The code is still using
signal
and thus UNIX only:The process for timing out an operations is described in the documentation for signal.
The basic idea is to use signal handlers to set an alarm for some time interval and raise an exception once that timer expires.
Note that this will only work on UNIX.
Here's an implementation that creates a decorator (save the following code as
timeout.py
).This creates a decorator called
@timeout
that can be applied to any long running functions.So, in your application code, you can use the decorator like so: