-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathrun_command_timeout.py
More file actions
44 lines (39 loc) · 1.37 KB
/
run_command_timeout.py
File metadata and controls
44 lines (39 loc) · 1.37 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import subprocess
import threading
""" Run system commands with timeout
"""
class Command(object):
def __init__(self, cmd):
self.cmd = cmd
self.process = None
self.out = None
def run_command(self, capture = False):
if not capture:
self.process = subprocess.Popen(self.cmd,shell=True)
self.process.communicate()
return
# capturing the outputs of shell commands
self.process = subprocess.Popen(self.cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,stdin=subprocess.PIPE)
out,err = self.process.communicate()
if len(out) > 0:
self.out = out.splitlines()
else:
self.out = None
# set default timeout to 2 minutes
def run(self, capture = False, timeout = 120):
thread = threading.Thread(target=self.run_command, args=(capture,))
thread.start()
thread.join(timeout)
if thread.is_alive():
print 'Command timeout, kill it: ' + self.cmd
self.process.terminate()
thread.join()
return self.out
'''basic test cases'''
# run shell command without capture
Command('pwd').run()
# capture the output of a command
date_time = Command('date').run(capture=True)
print date_time
# kill a command after timeout
Command('echo "sleep 10 seconds"; sleep 10; echo "done"').run(timeout=2)