My script needs to print a table while it is crunching some numbers. Its total run time is several hours, and I need it to add more and more rows to the printed table while it is running. I am trying to use PrettyTable, but I am open to other suggestions how else it can be accomplished. Here is an example of what I am trying to do:
from prettytable import PrettyTable
t = PrettyTable(['Name', 'Age'])
t.add_row(['Alice', 24])
print t
#do some work
t.add_row(['Bob', 19])
print t
The outcome that I get is this:
+-------+-----+
| Name | Age |
+-------+-----+
| Alice | 24 |
+-------+-----+
+-------+-----+
| Name | Age |
+-------+-----+
| Alice | 24 |
| Bob | 19 |
+-------+-----+
Is there a way not to print the entire table every time I add a row but print just a new row underneath of what has already been printed? I am trying to get somethig like this:
+-------+-----+
| Name | Age |
+-------+-----+
| Alice | 24 |
+-------+-----+
| Bob | 19 |
+-------+-----+
Left alignment for the first column would be a nice bonus.
The code below covers all what you have asked for IF you specify enough SPACES in the column names definition to cover the maximal width of all incoming items (thanks to all contributors to this question - I have used all of what came up here in the code provided below):
from __future__ import print_function
from prettytable import PrettyTable
t = PrettyTable(['Name ', ' Age'])
t.align['Name '] = 'l'
t.align[' Age'] = 'r'
t.hrules = 1
t.add_row(['Alice', 24])
print(t)
#do some work
t.add_row(['Bob', 19])
print( "\n".join(t.get_string().splitlines()[-2:]) )
#do some work
t.add_row(['AliceInWonderland', 1019])
print( "\n".join(t.get_string().splitlines()[-2:]) )
Here the output generated by the code above that works also for "AliceInWonderland" being 1019 years old :D :
+---------------------+--------+
| Name | Age |
+---------------------+--------+
| Alice | 24 |
+---------------------+--------+
| Bob | 19 |
+---------------------+--------+
| AliceInWonderland | 1019 |
+---------------------+--------+