prettytables在shell显示中动态刷新数据?

2024-03-27 22:59:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个bot,它循环各种活动(就像bot经常做的那样),并且我使用prettypetables来显示活动。在

https://code.google.com/p/prettytable/wiki/Tutorial

def promote(self):
    x = PrettyTable(["Bot ID", "Bot Name"])
    x.align["Bot ID"] = "l" # Left align city names
    x.padding_width = 1 # One space between column edges and contents (default)


    for bot_id, atts in self.bots.iteritems():               
            x.add_row([str(bot_id),atts['screenname']])

    print x   

理想情况下,我希望循环使用这些数据并更新数据,而不创建一个使用新行等的全新表。简单地说,是“刷新”。在

有没有一个shell命令可以删除最后一个输出并替换它?在


Tags: 数据httpsselfcomidbotgooglewiki
2条回答

如果我正确地理解了您的问题,您想知道如何在终端中移动光标。不幸的是,没有一种简单、便携的方法可以做到这一点。{/a1}就是这样做的。IIRC,Windows也可以使用这样的序列,但默认情况下是禁用的。在

总之,这里有一个小的演示脚本。注意,这个脚本可能不完全适用于所有*nix系统,这取决于它们使用的终端的确切细节;但是我将让Unix终端专家提供更正。:)

#! /usr/bin/env python

''' Simple demo of using ANSI escape codes to move the cursor '''

import sys
from time import sleep
from string import ascii_letters

#ANSI Control Sequence Introducer
csi = '\x1b['

def put(s): sys.stdout.write(s)

#Build a simple table row
def row(c, m, n):
    return '| ' + ' | '.join(n * [m*c]) + ' |'


def main():
    #Some data to make a table with
    data = ascii_letters

    #The number of rows per table section
    numrows = 6

    #Adjust data length to a multiple of numrows
    newlen = (len(data) // numrows) * numrows
    data = data[:newlen]

    m, n = 5, 7
    width = (m + 3) * n + 4

    print 'Table'.center(width, '-')
    for i, c in enumerate(data):
        if i and not i % numrows:
            sleep(2)
            #Move cursor up by numrows
            put('%s%dA' % (csi, numrows)) 
        print "%2d %s" % (i, row(c, m, n))


if __name__ == '__main__':
    main()

一个快速的解决方案是在每个print x之前打印空白行,如下所示:

def promote(self):
    x = PrettyTable(["Bot ID", "Bot Name"])
    x.align["Bot ID"] = "l" # Left align city names
    x.padding_width = 1 # One space between column edges and contents (default)


    for bot_id, atts in self.bots.iteritems():               
            x.add_row([str(bot_id),atts['screenname']])
    print '\n' * 1000 # as long as it clears the page text
    print x   

如果您绝对喜欢shell命令,您也可以将prettytable结果写入一个文件,然后调用subprocess并使用watch对其进行监视:

^{pr2}$

但我个人不喜欢这种方法。在

相关问题 更多 >