Skip to content

Instantly share code, notes, and snippets.

@e0ne
Created July 16, 2013 13:41
Show Gist options
  • Save e0ne/6008790 to your computer and use it in GitHub Desktop.
Save e0ne/6008790 to your computer and use it in GitHub Desktop.
# Original source:
# http://howto.pui.ch/post/37471155682/
# set-timeout-for-a-shell-command-in-python
import datetime
import os
import time
import signal
import subprocess
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"""
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()
if __name__ == '__main__':
out = timeout_command('cat /var/log/syslog', 1)
print(out)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment