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.
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
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:
cmd (as I see in your tags).while instead of for keep a counter variable up_count=1 and increase it at the end of each iteration.curses.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With