Skip to content

Instantly share code, notes, and snippets.

@vietlq
Forked from kirpit/bash.py
Created May 14, 2012 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vietlq/2693751 to your computer and use it in GitHub Desktop.
Save vietlq/2693751 to your computer and use it in GitHub Desktop.
Enables to run subprocess commands in a different thread with TIMEOUT option!
class Command(object):
'''
Enables to run subprocess commands in a different thread
with TIMEOUT option!
Based on jcollado's solution:
http://stackoverflow.com/questions/1191374/subprocess-with-timeout/4825933#4825933
'''
def __init__(self, cmd):
self.cmd = cmd
self.process = None
def run(self, timeout=None, **kwargs):
def target(**kwargs):
self.process = subprocess.Popen(self.cmd, **kwargs)
self.process.communicate()
thread = threading.Thread(target=target, kwargs=kwargs)
thread.start()
thread.join(timeout)
if thread.is_alive():
self.process.terminate()
thread.join()
return self.process.returncode
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment