簡體   English   中英

如何覆蓋/打印 Windows 命令行中的當前行?

[英]How can I overwrite/print over the current line in Windows command line?

在 Unix 上,我可以使用\\r (回車)或\\b (退格)來覆蓋 shell 中的當前行(打印已經可見的文本)。

我可以通過 Python 腳本在 Windows 命令行中實現相同的效果嗎?

我嘗試了 curses 模塊,但它似乎在 Windows 上不可用。

是:

import sys
import time

def restart_line():
    sys.stdout.write('\r')
    sys.stdout.flush()

sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()

我知道這很舊,但我想告訴我的版本(它在我的 PC 上在 cmd 中工作,但不在空閑狀態下)覆蓋 Python 3 中的一行:

>>> from time import sleep
>>> for i in range(400):
>>>     print("\r" + str(i), end="")
>>>     sleep(0.5)

編輯:它適用於 Windows 和 Ubuntu

import sys 
import time

for i in range(10):
    print '\r',         # print is Ok, and comma is needed.
    time.sleep(0.3)
    print i,
    sys.stdout.flush()  # flush is needed.

如果在 IPython-notebook 上,就像這樣:

import time
from IPython.display import clear_output

for i in range(10):
    time.sleep(0.25)
    print(i)
    clear_output(wait=True)

http://nbviewer.ipython.org/github/ipython/ipython/blob/master/examples/notebooks/Animations%20Using%20clear_output.ipynb

我剛遇到這個問題。 即使在 Windows 命令提示符中,您仍然可以使用\\r ,但是,它只會帶您回到上一個換行符 ( \\n )。

如果你做這樣的事情:

cnt = 0
print str(cnt)
while True:
    cnt += 1
    print "\r" + str(cnt)

你會得到:

0
1
2
3
4
5
...

那是因為\\r只會回到最后一行。 由於您已經在最后一個打印語句中寫入了一個換行符,因此您的光標會從一個新空行的開頭移動到同一新空行的開頭。

舉例說明,在打印第一個 0 后,您的光標將位於此處:

0
| # <-- Cursor

當您\\r ,您將轉到該行的開頭。 但你已經在行的開始。

解決方法是避免打印\\n字符,因此您的光標位於同一行上,而\\r正確覆蓋文本。 你可以用print 'text',來做到這一點。 逗號可防止打印換行符。

cnt = 0
print str(cnt),
while True:
    cnt += 1
    print "\r" + str(cnt),

現在它將正確地重寫行。

請注意,這是 Python 2.7,因此是print語句。

簡單的方法:)

import sys
from time import sleep
import os

#print("\033[y coordinate;[x coordinateH Hello")
os.system('cls')
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)
print("\033[1;1H  []")
sleep(0.2)
print("\033[1;1H    []")
sleep(0.2)
print("\033[1;1H      []")
sleep(0.2)
print("\033[1;1H        []")
sleep(0.2)
print("\033[1;1H      []")
sleep(0.2)
print("\033[1;1H    []")
sleep(0.2)
print("\033[1;1H  []")
sleep(0.2)
print("\033[1;1H[]")
sleep(0.2)

如果您只想更新上一​​行,則可以使用簡單的方法:

import time
for i in range(20):
    print str(i) + '\r',
    time.sleep(1)

最簡單的方法是使用兩個 \\r - 一個在開頭,一個在結尾

for i in range(10000):
    print('\r'+str(round(i*100/10000))+'%  Complete\r'),

它會很快

感謝這里所有有用的答案。 我需要這個:)

我發現 nosklo 的答案特別有用,但我希望通過將所需的輸出作為參數傳遞來完全包含在函數中。 另外,我真的不需要計時器,因為我希望在特定事件之后進行打印)。

這就是對我有用的技巧,我希望其他人覺得它有用:

import sys

def replace_cmd_line(output):
    """Replace the last command line output with the given output."""
    sys.stdout.write(output)
    sys.stdout.flush()
    sys.stdout.write('\r')
    sys.stdout.flush()

是的,這個問題是 11 年前提出的,但很酷。 我喜歡即興發揮。 對 nosklo 的回答的補充:

import sys
import time

def restart_line():
    sys.stdout.write("\r")
    sys.stdout.flush()

string_one = "some data that is very long..."
sys.stdout.write(string_one)
sys.stdout.flush()

time.sleep(2)
restart_line()

string_two = "shorter data"
if len(string_two) < len(string_one):
    string_two = string_two+(" "*int((len(string_one)-len(string_two))))
    # This will overwrite the characters that would be left on the console

sys.stdout.write(string_two)
sys.stdout.flush()

在 PyCharm 2020.3 和 Python 3.9 版上測試,為了覆蓋書面打印輸出,我使用以下內容:

from time import sleep

for x in range(10):
    print(f'\r {x}', end='')
    sleep(0.6)

這就是我主要用於我的程序的代碼。 使用end='\\r'將為我覆蓋整個文本,忽略睡眠。

在實際場景中,我設置如下:

    def progress_callback(progress):
        print(f'\rDownloading File: {progress.dlable.file_name}  Progress: ' + '{0:.2f}%'.format(progress.percent), end='')
        # `return True` if the download should be canceled
        return False

    print('\nDownload complete!)

overwrite 函數之后的打印必須在新行,否則之前的同一行將被覆蓋。

在 Windows (python 3) 上,它似乎可以工作(不直接使用 stdout):

import sys

for i in reversed(range(0,20)):
  time.sleep(0.1)
  if(i == 19):
    print(str(i), end='', file=sys.stdout)
  else:
    print("\r{0:{width}".format(str(i), width = w, fill = ' ', align = 'right'), end='', file=sys.stdout)
  sys.stdout.flush()
  w = len(str(i))

每次調用打印函數時都會更新同一行。

這個算法可以改進,但發布它是為了展示你可以做什么。 您可以根據需要修改該方法。

暫無
暫無

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

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