Reputation: 83
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
Reputation: 15872
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
.Upvotes: 2
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