在同一行打印(覆盖)未按预期工作

2024-04-28 23:59:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码如下:

print(' ⦾ Loading subcase decryption table...', end='')
codes_dict = load_codes(codes_file)
print('\r ✓ Subcase decryption table loaded.')

这样做的目的是让一条信息显示为一条反馈,说明某个东西正在运行(以及是什么):

>> ⦾ Loading subcase decryption table...

一旦完成,它必须由以下内容替换(在同一行):

>> ✓ Subcase decryption table loaded.

但这不起作用。相反,第一个print语句也必须以返回字符'\r'开头,就像print('\r ⦾ Loading subcase decryption table...', end='')一样,但是我不明白为什么。。在

如果它处于这样的循环中,那就非常有意义了:

^{pr2}$

有人能给我解释一下吗?在


Tags: 代码目的信息tableloaddictcodesfile
1条回答
网友
1楼 · 发布于 2024-04-28 23:59:38

原因(很可能)是您的shell是line buffered。任何发送到它的文本都会被缓冲到一定长度,或者直到遇到\r。这样做的原因是在程序写出单个字符时将开销最小化,从而将呈现内容推迟到最新但用户方便的时刻。在

The use of line buffering for interactive devices implies that output messages ending in a newline will appear immediately—which is usually what you want. Output that doesn’t end in a newline might or might not show up immediately, so if you want them to appear immediately, you should flush buffered output explicitly with fflush

行缓冲是第一行永远不会出现的原因;如果在该行前面加一个\r,那么就可以有效地刷新行缓冲区。在

解决方案通常是直接写入底层流或强制刷新缓冲区。在

相关问题 更多 >