coalescestreams.py 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. """Preprocessor for merging consecutive stream outputs for easier handling."""
  2. import re
  3. # Copyright (c) IPython Development Team.
  4. # Distributed under the terms of the Modified BSD License.
  5. from nbconvert.preprocessors import Preprocessor
  6. CR_PAT = re.compile(r".*\r(?=[^\n])")
  7. class CoalesceStreamsPreprocessor(Preprocessor):
  8. """
  9. Merge consecutive sequences of stream output into single stream
  10. to prevent extra newlines inserted at flush calls
  11. """
  12. def preprocess_cell(self, cell, resources, cell_index):
  13. """
  14. Apply a transformation on each cell. See base.py for details.
  15. """
  16. outputs = cell.get("outputs", [])
  17. if not outputs:
  18. return cell, resources
  19. last = outputs[0]
  20. new_outputs = [last]
  21. for output in outputs[1:]:
  22. if (
  23. output.output_type == "stream"
  24. and last.output_type == "stream"
  25. and last.name == output.name
  26. ):
  27. last.text += output.text
  28. else:
  29. new_outputs.append(output)
  30. last = output
  31. # process \r characters
  32. for output in new_outputs:
  33. if output.output_type == "stream" and "\r" in output.text:
  34. output.text = CR_PAT.sub("", output.text)
  35. cell.outputs = new_outputs
  36. return cell, resources