附加到上一行

问题描述 投票:1回答:1

我在Python中进行文件夹/文件处理。为了通知用户,我将一些消息输出到控制台。这些消息看起来类似于:

Creating folders...
DONE
Creating files...
DONE
All done!

如果过程很短,这很好,但在我的情况下,过程(和消息)并不短。我不想在成功/失败消息上浪费新的内容。我希望它们看起来像这样:

Creating folders... DONE
Creating files... DONE
All done!

诀窍是在特定任务完成后将“DONE”字符串附加到上一行。所以,首先我只看到:

Creating folders...

当任务完成后,它变为:

Creating folders... DONE

然后继续下一个任务。我试过没有结束这些行,但它不起作用:

print("Creating folders... ", end="")
time.sleep(2) # fake process
print("DONE")
time.sleep(1)
print("Creating files... ", end="")
time.sleep(2)
print("DONE")

好吧,它可以工作,但两个字符串(任务...结果)同时出现(任务完成后)。我没有看到我上面提到的转变。

我找到了另一种方法,移动到行的开头并替换字符串:

print("Creating folders... ", end="\r")
time.sleep(2) # fake process
print("Creating folders... DONE")
time.sleep(1)
print("Creating files... ", end="\r")
time.sleep(2)
print("Creating files... DONE")

这似乎产生了预期的效果,但我正在重复并扩展上一条消息。我宁愿只输出结果,而不是再次重复任务消息。

有一个更简单的解决方案吗?


另外,为什么我尝试的第一种方法不起作用?我打印文本,而不是结束。一段时间后,我添加另一个文本,这将附加到上一行,因为没有换行符。由于两张照片之间存在时差,我应该看到过渡,但我不知道。它们同时打印出来。这是为什么?

python python-3.x windows printing console
1个回答
5
投票

您需要在每个print语句(使用end="")之后刷新缓冲区,以确保消息立即被推送到控制台。请参阅print()文档。

带打印功能刷新参数的工作示例:

import time

print("Creating folders... ", end="", flush="True")
time.sleep(2)  # fake process
print("DONE")
time.sleep(1)
print("Creating folders... ", end="", flush="True")
time.sleep(2)
print("DONE")

手动冲洗工作示例:

import time
import sys

print("Creating folders... ", end="")
sys.stdout.flush()
time.sleep(2) # fake process
print("DONE")
time.sleep(1)
print("Creating files... ", end="")
sys.stdout.flush()
time.sleep(2)
print("DONE")

See it in action!

© www.soinside.com 2019 - 2024. All rights reserved.