|
8 | 8 | import shutil |
9 | 9 | import socket |
10 | 10 | import subprocess |
| 11 | +import sys |
11 | 12 | import tempfile |
12 | 13 | import textwrap |
13 | 14 | import time |
| 15 | +import threading |
14 | 16 | from typing import ( |
15 | 17 | IO, |
16 | 18 | Any, |
@@ -148,10 +150,39 @@ def kill(self) -> None: |
148 | 150 | self._own_ports.remove((hostname, port)) |
149 | 151 |
|
150 | 152 | def execute( |
151 | | - self, command: Sequence[Union[str, Path]], **kwargs: Any |
| 153 | + self, command: Sequence[Union[str, Path]], proc_name: Optional[str], **kwargs: Any |
152 | 154 | ) -> subprocess.Popen: |
153 | 155 | output_to = None if self.debug_mode else subprocess.DEVNULL |
154 | | - return subprocess.Popen(command, stderr=output_to, stdout=output_to, **kwargs) |
| 156 | + proc_name = proc_name or command[0] |
| 157 | + kwargs.setdefault("stdout", output_to) |
| 158 | + kwargs.setdefault("stderr", output_to) |
| 159 | + stream_stdout = stream_stderr = None |
| 160 | + if kwargs["stdout"] in (None, subprocess.STDOUT): |
| 161 | + kwargs["stdout"] = subprocess.PIPE |
| 162 | + def stream_stdout(): |
| 163 | + for line in proc.stdout: |
| 164 | + prefix = f"{time.time():.3f} {proc_name} ".encode() |
| 165 | + try: |
| 166 | + sys.stdout.buffer.write(prefix + line) |
| 167 | + except ValueError: |
| 168 | + # "I/O operation on closed file" |
| 169 | + pass |
| 170 | + if kwargs["stderr"] in (subprocess.STDOUT, None): |
| 171 | + kwargs["stdout"] = subprocess.PIPE |
| 172 | + def stream_stderr(): |
| 173 | + for line in proc.stdout: |
| 174 | + prefix = f"{time.time():.3f} {proc_name} ".encode() |
| 175 | + try: |
| 176 | + sys.stdout.buffer.write(prefix + line) |
| 177 | + except ValueError: |
| 178 | + # "I/O operation on closed file" |
| 179 | + pass |
| 180 | + proc = subprocess.Popen(command, **kwargs) |
| 181 | + if stream_stdout is not None: |
| 182 | + threading.Thread(target=stream_stdout, name="stream_stdout").start() |
| 183 | + if stream_stderr is not None: |
| 184 | + threading.Thread(target=stream_stderr, name="stream_stderr").start() |
| 185 | + return proc |
155 | 186 |
|
156 | 187 |
|
157 | 188 | class DirectoryBasedController(_BaseController): |
|
0 commit comments