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

时间:2014-10-26 06:41:09

标签: python shell module

我正在构建一个循环通过各种活动的机器人(就像机器人经常这样做)而且我正在使用“漂亮的桌子”。显示活动。

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命令删除最后一个输出并替换它?

2 个答案:

答案 0 :(得分:0)

快速解决方案是在每个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监控它,如下所示:

import subprocess
...
# instead of print x, write to a file
with open('result.txt', 'wb') as f:
    f.write(x)
...
# on main()
...
subprocess.call("watch -n 1 cat result.txt", shell=True)
...

我个人并不喜欢这种方法。

答案 1 :(得分:0)

如果我理解你的问题,你想知道如何在终端中移动光标。不幸的是,没有一种简单,便携的方法可以做到这一点。但是在Linux / Unix中运行的一种方法是使用ANSI escape sequences。 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()