I tried to write a “simple” Python function. All it had to do is to run a command line in a subprocess, and enforce a timeout on that subprocess.
Turns out that this “simple” goal is not so simple. I considered multiple approaches to solve this, and ran into interesting concurrency issues.
In this post I describe a solution based on Python subprocess
and various threading
constructs. I demonstrate a concurrency inconsistency I discovered when testing my solution on Linux and OS X.
The conclusion, if that’s all what you’re looking for, is that timer.is_alive()
is not a safe way to test whether a timer had expired!
Note: My experience is based on Python 2.7 with the default subprocess module from the standard library. If you’re on Python 3.3+, a timeout argument was added to subprocess. You can also install python-subprocess32, which brings this joy to Python 2.4-2.7.