You're probably much better off buffering all the messages you want together and using a textwrap.wrap
to present them!
You may be able to collect more easily via contextlib.redirect_stdout
see this answer to Capture stdout from a script?
If you have many threads or processes, collecting the outputs into some queue for display by a single one is a practical approach
Example Use
import io
import textwrap
from contextlib import redirect_stdout
buffer = io.StringIO()
with redirect_stdout(buffer):
# print() calls in this context will go to the buffer instead of stdout
# put whatever logic you were print()-ing from here
# likely one or several function calls
print("a very long string example" * 10)
print("1111111" * 20)
print("some\n new\r\nlines\n")
print("a string example with space " * 10)
# get one big string, replacing newlines with spaces
buffered_content = buffer.getvalue().replace("\n", " ")
# use a textwrap method to display the output, setting any options needed
# textwrap returns a list of lines, so they can be joined or printed individually
print("\n".join(textwrap.wrap(buffered_content)))
Output
% python3 test.py
a very long string examplea very long string examplea very long string
examplea very long string examplea very long string examplea very long
string examplea very long string examplea very long string examplea
very long string examplea very long string example 1111111111111111111
1111111111111111111111111111111111111111111111111111111111111111111111
111111111111111111111111111111111111111111111111111 some new lines
a string example with space a string example with space a string
example with space a string example with space a string example with
space a string example with space a string example with space a string
example with space a string example with space a string example with
space
If you want to continually display at some interval or quantity of content, you can keep the the last value of the textwrap
(beware: it may be an empty list if no input is provided).. as the input to a later .wrap()
to keep the line wrapping going until the end of your process