我正在用 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")
这似乎产生了预期的效果,但我正在重复和扩展之前的消息。我宁愿只输出结果,而不是再次重复任务消息。
有更简单的解决方案吗?
另外,为什么我试过的第一种方法不起作用?我打印一个文本,而不是结束该行。一段时间后,我添加了另一个文本并将其附加到上一行,因为没有换行符。由于两次打印之间存在时间差,我应该看到过渡,但我没有。它们同时打印。这是为什么?
最佳答案
您需要在每个打印语句(使用 end=""
)之后刷新缓冲区,以确保消息被立即推送到控制台。参见 print()文档。
带有 flush 打印函数参数的工作示例:
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")
关于python - 附加到上一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55648799/