Skip to content

Commit aa15c28

Browse files
committed
print and save both stdout and stderr in real time
1 parent c50737f commit aa15c28

File tree

1 file changed

+19
-17
lines changed

1 file changed

+19
-17
lines changed

python/bart.py

Lines changed: 19 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import tempfile as tmp
1111
import os
1212
import sys
13+
import threading
1314

1415
if __spec__.parent:
1516
from . import cfl
@@ -171,33 +172,34 @@ def bart_postprocess(nargout, ERR, infiles, infiles_kw, outfiles):
171172
def execute_cmd(cmd):
172173
"""
173174
Execute a command in a shell.
174-
Print and catch the output.
175+
Print and catch the output (stdout + stderr) in real time.
175176
"""
176177

177-
errcode = 0
178-
stdout = ""
179-
stderr = ""
180-
181178
# remove empty strings from cmd
182179
cmd = [item for item in cmd if len(item)]
183180

184181
# execute cmd
185182
proc = sp.Popen(cmd, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True)
186183

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()
192189

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))
199194

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)
201203

202204

203205

0 commit comments

Comments
 (0)