Here is a code example to print some numbers at the same cursor position of the console, without moving the characters from place.
Code Example
from sys import stdout
from time import sleep
for i in range(1,20):
stdout.write("\r%d" % i)
stdout.flush()
sleep(1)
stdout.write("\n") # move the cursor to the next line
Question
Does this same approach work if we need to print an entire table over and over at the same position, without creating a new table line, making it altogether
static
.
My aim is to make the code given at the buttom to work, same as the code example
shared above.
When printing a table on console the headers of the table must not change, but the values (row elements) passed must dynamically change at the same cell positions, iterating the values passed.
Below is the code I aimed for.
from prettytable import PrettyTable
from sys import stdout
from time import sleep
t = PrettyTable(['Name', 'Age'])
lis = [['Alice', 25],['Alice', 20],['Man', 20]]
for x in lis:
t.add_row(x)
print(t, end='\r')
t.clear_rows()
sleep(1)
stdout.write("\n")
In here, iterating the print(t, end='\r')
is printing the tables everytime onto a new line.
I wish to see that table printed for the first iteration (for loop), gets completely replaced by the tables of the next iterations and so on.
curseXcel and curses
can make this happen. Please check all the different methods available with curseXcel.
Prerequisites
Install
sudo pip install curseXcel
import curses
from curseXcel import Table
from time import sleep
def main(stdscr):
y = 0
table = Table(stdscr, 2, 4 ,10, 45, 20, spacing=2, col_names=True) # This sets the table rows, columns, width, height and spacing.
for x in [['Name',0], ['Age',1], ['Job',2],['Country', 3]]:
# This sets the header columns.
table.set_column_header(x[0],x[1])
table.delete_row(1) # This deletes the additional row.
nameList = [["Alice", 25, 'Painter', 'AUS'],["Bob", 32, 'cop', 'UK'],["Thinker", 20, 'coder', 'UK'],["Adam", 70, 'None', 'USA'],["Jessi", 14, 'None', 'BZA'],["Leo", 30, 'Army', 'India']]
# This above list contains data you need to loop through
while (y != 'q'): # This makes the loop to repeat indefinitely.
#y= stdscr.getkey()
for x in nameList:
sleep(1)
# This sets the elements of the list to the respective positions.
table.set_cell(0,0, x[0])
table.set_cell(0,1, x[1])
table.set_cell(0,2, x[2])
table.set_cell(0,3, x[3])
table.refresh()
stdscr = curses.initscr()
curses.noecho()
curses.cbreak()
stdscr.keypad(True)
curses.wrapper(main)
curses.nocbreak()
stdscr.keypad(False)
curses.echo()
curses.endwin() # End curses
Output