|
10 | 10 | import tempfile as tmp |
11 | 11 | import os |
12 | 12 | import sys |
| 13 | +import threading |
13 | 14 |
|
14 | 15 | if __spec__.parent: |
15 | 16 | from . import cfl |
@@ -171,33 +172,34 @@ def bart_postprocess(nargout, ERR, infiles, infiles_kw, outfiles): |
171 | 172 | def execute_cmd(cmd): |
172 | 173 | """ |
173 | 174 | Execute a command in a shell. |
174 | | - Print and catch the output. |
| 175 | + Print and catch the output (stdout + stderr) in real time. |
175 | 176 | """ |
176 | 177 |
|
177 | | - errcode = 0 |
178 | | - stdout = "" |
179 | | - stderr = "" |
180 | | - |
181 | 178 | # remove empty strings from cmd |
182 | 179 | cmd = [item for item in cmd if len(item)] |
183 | 180 |
|
184 | 181 | # execute cmd |
185 | 182 | proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True) |
186 | 183 |
|
187 | | - # print to stdout |
188 | | - for stdout_line in iter(proc.stdout.readline, ""): |
189 | | - stdout += stdout_line |
190 | | - print(stdout_line, end="") |
191 | | - proc.stdout.close() |
| 184 | + def read_stream(stream, buffer, prefix=""): |
| 185 | + for line in iter(stream.readline, ""): |
| 186 | + buffer.append(line) |
| 187 | + print(prefix + line, end="") |
| 188 | + stream.close() |
192 | 189 |
|
193 | | - # in case of error, print to stderr |
194 | | - errcode = proc.wait() |
195 | | - if errcode: |
196 | | - stderr = "".join(proc.stderr.readlines()) |
197 | | - print(stderr) |
198 | | - proc.stderr.close() |
| 190 | + stdout_lines, stderr_lines = [], [] |
| 191 | + |
| 192 | + t_out = threading.Thread(target=read_stream, args=(proc.stdout, stdout_lines)) |
| 193 | + t_err = threading.Thread(target=read_stream, args=(proc.stderr, stderr_lines)) |
199 | 194 |
|
200 | | - return errcode, stdout, stderr |
| 195 | + t_out.start() |
| 196 | + t_err.start() |
| 197 | + |
| 198 | + t_out.join() |
| 199 | + t_err.join() |
| 200 | + |
| 201 | + errcode = proc.wait() |
| 202 | + return errcode, "".join(stdout_lines), "".join(stderr_lines) |
201 | 203 |
|
202 | 204 |
|
203 | 205 |
|
|
0 commit comments