3 # © Copyright 2021-2022, Scott Gasch
5 """Helper methods concerned with executing subprocesses."""
14 from typing import List, Optional
16 logger = logging.getLogger(__file__)
19 def cmd_showing_output(
22 """Kick off a child process. Capture and emit all output that it
23 produces on stdout and stderr in a character by character manner
24 so that we don't have to wait on newlines. This was done to
25 capture the output of a subprocess that created dots to show
26 incremental progress on a task and render it correctly.
29 command: the command to execute
32 the exit status of the subprocess once the subprocess has
36 prints all output of the child process (stdout or stderr)
39 line_enders = set([b'\n', b'\r'])
40 sel = selectors.DefaultSelector()
41 with subprocess.Popen(
45 stdout=subprocess.PIPE,
46 stderr=subprocess.PIPE,
47 universal_newlines=False,
49 sel.register(p.stdout, selectors.EVENT_READ) # type: ignore
50 sel.register(p.stderr, selectors.EVENT_READ) # type: ignore
53 for key, _ in sel.select():
54 char = key.fileobj.read(1) # type: ignore
56 sel.unregister(key.fileobj)
57 if len(sel.get_map()) == 0:
62 if key.fileobj is p.stdout:
63 os.write(sys.stdout.fileno(), char)
64 if char in line_enders:
67 os.write(sys.stderr.fileno(), char)
68 if char in line_enders:
74 def cmd_exitcode(command: str, timeout_seconds: Optional[float] = None) -> int:
75 """Run a command silently and return its exit code once it has
76 finished. If timeout_seconds is provided and the command runs too
77 long it will raise a TimeoutExpired exception.
80 command: the command to run
81 timeout_seconds: the max number of seconds to allow the subprocess
82 to execute or None to indicate no timeout
85 the exit status of the subprocess once the subprocess has
88 >>> cmd_exitcode('/bin/echo foo', 10.0)
91 >>> cmd_exitcode('/bin/sleep 2', 0.01)
92 Traceback (most recent call last):
94 subprocess.TimeoutExpired: Command '['/bin/bash', '-c', '/bin/sleep 2']' timed out after 0.01 seconds
97 return subprocess.check_call(["/bin/bash", "-c", command], timeout=timeout_seconds)
100 def cmd(command: str, timeout_seconds: Optional[float] = None) -> str:
101 """Run a command and capture its output to stdout and stderr into a
102 string buffer. Return that string as this function's output.
103 Raises subprocess.CalledProcessError or TimeoutExpired on error.
106 command: the command to run
107 timeout_seconds: the max number of seconds to allow the subprocess
108 to execute or None to indicate no timeout
111 The captured output of the subprocess' stdout as a string buffer
113 >>> cmd('/bin/echo foo')[:-1]
116 >>> cmd('/bin/sleep 2', 0.01)
117 Traceback (most recent call last):
119 subprocess.TimeoutExpired: Command '/bin/sleep 2' timed out after 0.01 seconds
122 ret = subprocess.run(
125 stdout=subprocess.PIPE,
126 stderr=subprocess.STDOUT,
128 timeout=timeout_seconds,
130 return ret.decode("utf-8")
133 def run_silently(command: str, timeout_seconds: Optional[float] = None) -> None:
134 """Run a command silently but raise subprocess.CalledProcessError if
135 it fails and raise a TimeoutExpired if it runs too long.
138 command: the command to run
139 timeout_seconds: the max number of seconds to allow the subprocess
140 to execute or None to indicate no timeout
143 No return value; error conditions (including non-zero child process
144 exits) produce exceptions.
146 >>> run_silently("/usr/bin/true")
148 >>> run_silently("/usr/bin/false")
149 Traceback (most recent call last):
151 subprocess.CalledProcessError: Command '/usr/bin/false' returned non-zero exit status 1.
157 stderr=subprocess.DEVNULL,
158 stdout=subprocess.DEVNULL,
159 capture_output=False,
161 timeout=timeout_seconds,
165 def cmd_in_background(command: str, *, silent: bool = False) -> subprocess.Popen:
166 """Spawns a child process in the background and registers an exit
167 handler to make sure we kill it if the parent process (us) is
171 command: the command to run
172 silent: do not allow any output from the child process to be displayed
173 in the parent process' window
176 the :class:`Popen` object that can be used to communicate
177 with the background process.
179 args = shlex.split(command)
181 subproc = subprocess.Popen(
183 stdin=subprocess.DEVNULL,
184 stdout=subprocess.DEVNULL,
185 stderr=subprocess.DEVNULL,
188 subproc = subprocess.Popen(args, stdin=subprocess.DEVNULL)
190 def kill_subproc() -> None:
192 if subproc.poll() is None:
193 logger.info('At exit handler: killing %s (%s)', subproc, command)
195 subproc.wait(timeout=10.0)
196 except BaseException as be:
199 atexit.register(kill_subproc)
203 def cmd_list(command: List[str]) -> str:
204 """Run a command with args encapsulated in a list and return the
205 output text as a string. Raises subprocess.CalledProcessError.
207 ret = subprocess.run(command, capture_output=True, check=True).stdout
208 return ret.decode("utf-8")
211 if __name__ == '__main__':