Over a million developers have joined DZone.

Python 101: How to Timeout a Subprocess

DZone's Guide to

Python 101: How to Timeout a Subprocess

Check out Mike Driscoll's tutorial on using Python's threading module's Timer class to timeout a subprocess.

· Web Dev Zone ·
Free Resource

Bugsnag monitors application stability, so you can make data-driven decisions on whether you should be building new features, or fixing bugs. Learn more.

The other day I ran into a use case where I needed to communicate with a subprocess I had started but I needed it to timeout. Unfortunately, Python 2 does not have a way to timeout the communicate method call so it just blocks until it either returns or the process itself closes. There are lots of different approaches that I found on StackOverflow, but I think my favorite was using Python’s threading module’s Timer class:

import subprocess

from threading import Timer

kill = lambda process: process.kill()
cmd = ['ping', 'www.google.com']
ping = subprocess.Popen(
    cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

my_timer = Timer(5, kill, [ping])

    stdout, stderr = ping.communicate()

This particular example doesn’t follow the use case I encountered exactly, but it’s close. Basically, what we have here is a long running process that we want to interact with. On Linux, if you call ping it will run indefinitely. So it makes a good example. In this case, we write killing lambda that will call the process’s kill method. Then we start the ping command, put it in a timer that’s set to expire in five seconds, and start the Timer. While the process runs, we collect its stdout and stderr and then the process dies. Finally, we clean up by stopping the timer.

Image title

Python 3.5 added the run function which accepts a timeout parameter. According to the documentation, it will be passed to the subprocess’s communicate method and TimeoutExpired exception will be raised should the process time out. Let’s try it:

>>> import subprocess
>>> cmd = ['ping', 'www.google.com']
>>> subprocess.run(cmd, timeout=5)
PING www.google.com ( 56(84) bytes of data.
64 bytes from ord31s21-in-f4.1e100.net ( icmp_seq=1 ttl=55 time=16.3 ms
64 bytes from ord31s21-in-f4.1e100.net ( icmp_seq=2 ttl=55 time=19.4 ms
64 bytes from ord31s21-in-f4.1e100.net ( icmp_seq=3 ttl=55 time=20.0 ms
64 bytes from ord31s21-in-f4.1e100.net ( icmp_seq=4 ttl=55 time=19.4 ms
64 bytes from ord31s21-in-f4.1e100.net ( icmp_seq=5 ttl=55 time=17.0 ms
Traceback (most recent call last):
  Python Shell, prompt 3, line 1
  File "/usr/local/lib/python3.5/subprocess.py", line 711, in run
subprocess.TimeoutExpired: Command '['ping', 'www.google.com']' timed out after 5 seconds

It obviously worked the way it is documented. To be truly useful, we would probably want to wrap our subprocess call in an exception handler:

>>> try:
...     subprocess.run(cmd, timeout=5)
... except subprocess.TimeoutExpired:
...     print('process ran too long')
PING www.google.com ( 56(84) bytes of data.
64 bytes from ord31s21-in-f196.1e100.net ( icmp_seq=1 ttl=55 time=18.3 ms
64 bytes from ord31s21-in-f196.1e100.net ( icmp_seq=2 ttl=55 time=21.1 ms
64 bytes from ord31s21-in-f196.1e100.net ( icmp_seq=3 ttl=55 time=22.7 ms
64 bytes from ord31s21-in-f196.1e100.net ( icmp_seq=4 ttl=55 time=20.3 ms
64 bytes from ord31s21-in-f196.1e100.net ( icmp_seq=5 ttl=55 time=16.8 ms
process ran too long

Now that we can catch the exception, we can continue doing something else or save the error exception. Interestingly enough, the timeout parameter was added to the subprocess module in Python 3.3. You can use it in subprocess.call, check_output, and check_call. It’s also available in Popen.wait().

Monitor application stability with Bugsnag to decide if your engineering team should be building new features on your roadmap or fixing bugs to stabilize your application.Try it free.

python ,timeouts ,timers

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}