1

这是一个代码示例,用于在控制台的相同光标位置打印一些数字,而无需从位置移动字符。

代码示例

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

问题

如果我们需要在同一位置一遍又一遍地打印整个表格,而不创建新的表格行,那么这种方法是否有效static


我的目标是使底部给出的代码能够工作,与code example上面共享的相同。

在控制台上打印表格时,表格的标题不得更改,但传递的值(行元素)必须在相同的单元格位置动态更改,迭代传递的值。

下面是我的目标代码。

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")

在这里,迭代print(t, end='\r')就是每次将表格打印到新行上。

我希望看到为第一次迭代(for 循环)打印的表,被下一次迭代的表完全取代,依此类推。

4

1 回答 1

0

curseXcelcurses可以做到这一点。请检查 curseXcel 可用的所有不同方法。

先决条件

安装

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

输出

这就是输出的样子

于 2020-10-09T05:57:11.973 回答