簡體   English   中英

Python 3 打印時清除線條

[英]Clear line when printing in Python 3

我正在嘗試為加載元素清除一行,我有它的單行打印部分,我只需要這個

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 ?

這是我到目前為止的代碼:

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(".")

這給了我這個輸出(最后階段):

loading.....

我想刪除上面的行,這樣我就可以多次使用加載序列。

我相信這些調整會得到你想要的:

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()

兩個變化:

  1. 在 print 中設置flush=True確保每個點在 sleep 語句之間打印,否則它們將立即顯示。
  2. printf("\r{:12}\r".format(''))清除該行。 '\r'是回車,將 cursor 移動到開頭,然后打印一些空格以“清除”(覆蓋)加載文本(這是 12 個字符),然后再次回車以打印新的加載消息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM