def __runProcessWithFilteredOutput(self, proc: subprocess.Popen, logfile: "typing.Optional[io.FileIO]",
stdoutFilter: "typing.Callable[[bytes], None]", cmdStr: str):
logfileLock = threading.Lock() # we need a mutex so the logfile line buffer doesn't get messed up
stderrThread = None
if logfile:
# use a thread to print stderr output and write it to logfile (not using a thread would block)
stderrThread = threading.Thread(target=self._handleStdErr, args=(logfile, proc.stderr, logfileLock, self))
stderrThread.start()
for line in proc.stdout:
with logfileLock: # make sure we don't interleave stdout and stderr lines
if logfile:
logfile.write(line)
if stdoutFilter:
stdoutFilter(line)
else:
sys.stdout.buffer.write(line)
flushStdio(sys.stdout)
retcode = proc.wait()
if stderrThread:
stderrThread.join()
# Not sure if the remaining call is needed
remainingErr, remainingOut = proc.communicate()
if remainingErr:
print("Process had remaining stderr:", remainingErr)
sys.stderr.buffer.write(remainingErr)
if logfile:
logfile.write(remainingOut)
if remainingOut:
print("Process had remaining stdout:", remainingOut)
sys.stdout.buffer.write(remainingOut)
if logfile:
logfile.write(remainingErr)
if stdoutFilter and self._lastStdoutLineCanBeOverwritten:
# add the final new line after the filtering
sys.stdout.buffer.write(b"\n")
if retcode:
message = "Command \"%s\" failed with exit code %d.\n" % (cmdStr, retcode)
if logfile:
message += "See " + logfile.name + " for details."
raise SystemExit(message)
评论列表
文章目录