1 # SPDX-License-Identifier: GPL-2.0
2 # Copyright (c) 2015-2016, NVIDIA CORPORATION. All rights reserved.
4 # Logic to spawn a sub-process and interact with its stdio.
13 class Timeout(Exception):
14 """An exception sub-class that indicates that a timeout occurred."""
18 """Represents the stdio of a freshly created sub-process. Commands may be
19 sent to the process, and responses waited for.
22 output: accumulated output from expect()
25 def __init__(self, args, cwd=None):
26 """Spawn (fork/exec) the sub-process.
29 args: array of processs arguments. argv[0] is the command to
31 cwd: the directory to run the process in, or None for no change.
40 self.logfile_read = None
44 # http://stackoverflow.com/questions/7857352/python-regex-to-match-vt100-escape-sequences
45 self.re_vt100 = re.compile(r'(\x1b\[|\x9b)[^@-_]*[@-_]|\x1b[@-_]', re.I)
47 (self.pid, self.fd) = pty.fork()
50 # For some reason, SIGHUP is set to SIG_IGN at this point when
51 # run under "go" (www.go.cd). Perhaps this happens under any
52 # background (non-interactive) system?
53 signal.signal(signal.SIGHUP, signal.SIG_DFL)
56 os.execvp(args[0], args)
58 print('CHILD EXECEPTION:')
65 self.poll = select.poll()
66 self.poll.register(self.fd, select.POLLIN | select.POLLPRI | select.POLLERR | select.POLLHUP | select.POLLNVAL)
72 """Send unix signal "sig" to the child process.
75 sig: The signal number to send.
81 os.kill(self.pid, sig)
84 """Determine whether the child process is still running.
90 Boolean indicating whether process is alive.
96 w = os.waitpid(self.pid, os.WNOHANG)
103 def send(self, data):
104 """Send data to the sub-process's stdin.
107 data: The data to send to the process.
113 os.write(self.fd, data.encode(errors='replace'))
115 def expect(self, patterns):
116 """Wait for the sub-process to emit specific data.
118 This function waits for the process to emit one pattern from the
119 supplied list of patterns, or for a timeout to occur.
122 patterns: A list of strings or regex objects that we expect to
123 see in the sub-process' stdout.
126 The index within the patterns array of the pattern the process
130 Timeout, if the process did not emit any of the patterns within
134 for pi in range(len(patterns)):
135 if type(patterns[pi]) == type(''):
136 patterns[pi] = re.compile(patterns[pi])
138 tstart_s = time.time()
143 for pi in range(len(patterns)):
144 pattern = patterns[pi]
145 m = pattern.search(self.buf)
148 if earliest_m and m.start() >= earliest_m.start():
153 pos = earliest_m.start()
154 posafter = earliest_m.end()
155 self.before = self.buf[:pos]
156 self.after = self.buf[pos:posafter]
157 self.output += self.buf[:posafter]
158 self.buf = self.buf[posafter:]
162 tdelta_ms = (tnow_s - tstart_s) * 1000
163 poll_maxwait = self.timeout - tdelta_ms
164 if tdelta_ms > self.timeout:
168 events = self.poll.poll(poll_maxwait)
171 c = os.read(self.fd, 1024).decode(errors='replace')
174 if self.logfile_read:
175 self.logfile_read.write(c)
177 # count=0 is supposed to be the default, which indicates
178 # unlimited substitutions, but in practice the version of
179 # Python in Ubuntu 14.04 appears to default to count=2!
180 self.buf = self.re_vt100.sub('', self.buf, count=1000000)
182 if self.logfile_read:
183 self.logfile_read.flush()
186 """Close the stdio connection to the sub-process.
188 This also waits a reasonable time for the sub-process to stop running.
199 if not self.isalive():
203 def get_expect_output(self):
204 """Return the output read by expect()
207 The output processed by expect(), as a string.