簡體   English   中英

如何在 python 的終端頂部打印新的 output?

[英]How to print new output at top of terminal in python?

How could I go about printing the latest output at the top of the terminal so instead of new output being constantly added to the bottom of the window, it is stacked on the top?

示例程序:

for x in range(4):
    print(x)

Output:

0
1
2
3

所需的 output:

3
2
1
0

編輯:這個例子只是一個簡單的視覺效果,可以更好地理解這個問題。 我的實際程序將實時返回數據,如果有意義的話,我有興趣將最新的數據打印到頂部。

使用 ANSII 轉義碼移動 Cursor

一種方法是為每一行繼續打印適當數量的go-up-to-beginnig ANSII 轉義字符,但這意味着,您需要在每次迭代中存儲項目:

historical_output = []
padding = -1
UP = '\033[F'

for up_count, x in enumerate(range(4), start=1):
    curr_len = len(str(x))

    if curr_len > padding:
        padding = curr_len

    historical_output.insert(0, x)
    print(UP * up_count)
    print(*historical_output, sep='\n'.rjust(padding))

Output:

3
2
1
0

將 Output 限制為一定的行數

如果要將 output 限制為最后n行,可以使用collections.deque

from collections import deque

max_lines_to_display = 5        # If this is None, falls back to above code
historical_output = deque(maxlen=max_lines_to_display)
padding = -1
up_count = 1
UP = '\033[F'

for x in range(12):
    curr_len = len(str(x))

    if curr_len > padding:
        padding = curr_len

    historical_output.appendleft(x)
    print(UP * up_count)

    if (max_lines_to_display is None 
        or up_count < max_lines_to_display+1):
        up_count += 1

    print(*historical_output, sep='\n'.rjust(padding))

Output:

11
10
9
8
7

\033[F是一個ANSII Escape Code ,它將 cursor 移動到上一行的開頭。

筆記:

  • 這不適用於所有類型的終端,但適用於 windows cmd (正如我在您的標簽中看到的那樣)。
  • 如果您需要使用while不是for保持計數器變量up_count=1並在每次迭代結束時增加它。
  • 這種方法適用於有限數量的行,但如果你想永遠使用 go,你應該使用類似curses的東西。

你可以嘗試使用這個

for x in list(range(4))[::-1]:
    print(x)

看來您不能輕易反轉終端順序。

但是使用python你可以使用這個:

for i in reversed(range(10)):
    print(i)
# Output
9
8
7
6
5
4
3
2
1
0

暫無
暫無

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

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