mattwatkins
mattwatkins

Reputation: 83

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?

Example program:

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

Output:

0
1
2
3

Desired output:

3
2
1
0

Edit: The example is just a simple visual to understand the question better. My actual programs will be returning data in real time, which I am interested in having the latest printed to the top if that makes sense.

Upvotes: 2

Views: 1596

Answers (3)

Sayandip Dutta
Sayandip Dutta

Reputation: 15872

Using ANSII Escape Code to Move Cursor

One way would be keep printing appropriate number of go-up-to-beginnig ANSII Escape Characters for each line, but that means, you will need to store the items in each iteration:

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

Restricting the Output to Certain Number of Lines

If you want to restrict the output to last n lines, you can use 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 is an ANSII Escape Code that moves the cursor to the start of the previous line.

NOTE:

  • This does not work on all types of terminals, but will work on windows cmd (as I see in your tags).
  • If you need to use while instead of for keep a counter variable up_count=1 and increase it at the end of each iteration.
  • This approach is fine for limited amount of lines, but if you want to go on forever, you should use something along the lines of curses.

Upvotes: 2

ChainYo
ChainYo

Reputation: 68

It seems that you cannot inverse the terminal order easily.

But with python you can use this:

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

Upvotes: 0

asyncg
asyncg

Reputation: 163

You can try to use this

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

Upvotes: 1

Related Questions