处理多行回车



我遇到了这个问题。

当您有一个r字符串时,您可以更新打印行:

print('r' + "Some string", end='')
print('r' + "Updated string", end='')

然而,如果字符串太长,它将被截断到一个新的控制台行,这将强制换行,从而破坏"无缝"。字符串更新。

有办法防止这种情况吗?

最好将所有想要的消息缓冲在一起,并使用textwrap.wrap来呈现它们!

你可以通过contextlib.redirect_stdout更容易地收集看到这个答案从脚本捕获标准输出?

如果您有许多线程或进程,将输出收集到某个队列中供单个线程或进程显示是一种实用的方法

示例用

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("somen newrnlinesn")
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)))

% 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

如果您想以一定的间隔或数量连续显示内容,您可以保留textwrap的最后一个值(注意:如果没有提供输入,它可能是一个空列表)。作为后续.wrap()的输入,以保持换行直到进程结束

最新更新