Skip to content

Instantly share code, notes, and snippets.

@hellysmile
Created May 26, 2013 15:09
Show Gist options
  • Save hellysmile/5653056 to your computer and use it in GitHub Desktop.
Save hellysmile/5653056 to your computer and use it in GitHub Desktop.
python subprocess with timeout
def timeout_command(command, timeout):
"""call shell-command and either return its output or kill it
if it doesn't normally exit within timeout seconds and return None"""
import subprocess, datetime, os, time, signal
start = datetime.datetime.now()
process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
while process.poll() is None:
time.sleep(0.1)
now = datetime.datetime.now()
if (now - start).seconds> timeout:
os.kill(process.pid, signal.SIGKILL)
os.waitpid(-1, os.WNOHANG)
return None
return process.stdout.read()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment