-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinteractive_subprocess.py
More file actions
38 lines (33 loc) · 1.62 KB
/
interactive_subprocess.py
File metadata and controls
38 lines (33 loc) · 1.62 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
import os
import time
import select
import subprocess
class InteractiveSubrocess(object):
def __init__(self, command):
self._command = command
self._proc = subprocess.Popen(self._command, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
self._poller = select.epoll()
self._poller.register(self._proc.stdout.fileno(), select.EPOLLIN)
def waitForProcessToPrintString(self, string, timeout=5):
print "Waiting for setup util to print '%s'" % (string,)
output = ""
timeOfStart = time.time()
while not output.endswith(string):
timeUntilExpiration = max(timeOfStart + timeout - time.time(), 0)
flags = self._poller.poll(timeout=timeUntilExpiration)
timeSinceStart = time.time() - timeOfStart
hasTimeoutExpired = timeSinceStart > timeout
if hasTimeoutExpired:
message = ("Command %(command)s did not print '%(expected)s' on time (timeout: %(timeout)d)"
% dict(command=self._command, expected=string, timeout=timeout))
raise Exception(message)
if flags:
output += self._proc.stdout.read(1)
def write(self, string):
self._proc.stdin.write(string)
def waitToFinishSuccessfully(self):
returncode = self._proc.wait()
if returncode != os.EX_OK:
msg = ("Command %(command)s failed (return code %(returncode)d. Output from setup: %(output)s"
% dict(command=self._command, returncode=returncode, output=self._proc.stdout.read()))