简体   繁体   English

Python 3 打印时清除线条

[英]Clear line when printing in Python 3

I am trying to clear a line for a loading element, I have the printing-on-one-line part of it, I just need this我正在尝试为加载元素清除一行,我有它的单行打印部分,我只需要这个

I have consulted some websites(mainly this one) and I cannot find an answer, I am using https://trinket.io as my coder, I also have python from https://python.org , can you find code that works? I have consulted some websites(mainly this one) and I cannot find an answer, I am using https://trinket.io as my coder, I also have python from https://python.org , can you find code that works ?

Here is the code I have so far:这是我到目前为止的代码:

import functools

printf = functools.partial(print, end="")

loading():
    printf("loading")
    printf(".")
    time.sleep(.3)
    printf(".")
    time.sleep(.3)
    printf(".")
    time.sleep(.3)
    printf(".")
    time.sleep(.3)
    printf(".")

Which gives me this output(final stage):这给了我这个输出(最后阶段):

loading.....

I want to delete the line above so I can use the loading sequence multiple times.我想删除上面的行,这样我就可以多次使用加载序列。

I believe these adjustments will get what you want:我相信这些调整会得到你想要的:

import functools
import time

printf = functools.partial(print, end="", flush=True)

def loading():
    printf("\r{:12}\r".format(''))
    printf("loading")
    printf(".")
    time.sleep(.3)
    printf(".")
    time.sleep(.3)
    printf(".")
    time.sleep(.3)
    printf(".")
    time.sleep(.3)
    printf(".")

loading()
time.sleep(2)
loading()

Two changes:两个变化:

  1. Setting flush=True in print makes sure that each dot prints between sleep statements, otherwise they'll all be displayed at once.在 print 中设置flush=True确保每个点在 sleep 语句之间打印,否则它们将立即显示。
  2. printf("\r{:12}\r".format('')) clears the line. printf("\r{:12}\r".format(''))清除该行。 '\r' is carriage return, moving cursor to beginning, then it prints some blank spaces to "clear" (overwrite) the loading text (which is 12 characters), and then does carriage return again to print a new loading message. '\r'是回车,将 cursor 移动到开头,然后打印一些空格以“清除”(覆盖)加载文本(这是 12 个字符),然后再次回车以打印新的加载消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM