[PYTHON] Terminal에 table 출력하기(Source Code / Python / Terminal / Table)

요즘 할일이 참 산더미네요.. 회사에 개인적으로 하는거까지… :(

따로 간단하게 만들고있는 SSL Vulnerability Scanner인 a2sv에 어떻게하면 report 부분을 예쁘게 꾸밀가 고민하던 중 stackoverflow에서 좋은 코드를 하나 발견하였습니다. 별다른 모듈이나 라이브러리 없이 쉽게 table을 출력할 수 있도록 만들어놓은 간단한 class 이죠. 쓸만한 코드여서 메모할겸 작성합니다.

TablePrinter Class


class TablePrinter(object): 
    "Print a list of dicts as a table" 
    def __init__(self, fmt, sep=' ', ul=None): 
        """         
        @param fmt: list of tuple(heading, key, width) 
                        heading: str, column label 
                        key: dictionary key to value to print 
                        width: int, column width in chars 
        @param sep: string, separation between columns 
        @param ul: string, character to underline column label, or None for no underlining 
        """ 
        super(TablePrinter,self).__init__() 
        self.fmt   = str(sep).join('{lb}{0}:{1}{rb}'.format(key, width, lb='{', rb='}') for heading,key,width in fmt) 
        self.head  = {key:heading for heading,key,width in fmt} 
        self.ul    = {key:str(ul)*width for heading,key,width in fmt} if ul else None 
        self.width = {key:width for heading,key,width in fmt} 

    def row(self, data): 
        return self.fmt.format(**{ k:str(data.get(k,''))[:w] for k,w in self.width.iteritems() }) 

    def __call__(self, dataList): 
        _r = self.row 
        res = [_r(data) for data in dataList] 
        res.insert(0, _r(self.head)) 
        if self.ul: 
            res.insert(1, _r(self.ul)) 
        return '\n'.join(res) 

Table 내용 정의 구간


data = [ 
    {'classid':'foo', 'dept':'bar', 'coursenum':'foo', 'area':'bar', 'title':'foo'}, 
    {'classid':'yoo', 'dept':'hat', 'coursenum':'yoo', 'area':'bar', 'title':'hat'}, 
    {'classid':'yoo'*9, 'dept':'hat'*9, 'coursenum':'yoo'*9, 'area':'bar'*9, 'title':'hathat'*9} 
] 

fmt = [ 
    ('ClassID',       'classid',   11), 
    ('Dept',          'dept',       8), 
    ('Course Number', 'coursenum', 20), 
    ('Area',          'area',       8), 
    ('Title',         'title',     30) 
] 

print( TablePrinter(fmt, ul='=')(data) ) 

Output


ClassID     Dept     Course Number        Area     Title                          
=========== ======== ==================== ======== ============================== 
foo         bar      foo                  bar      foo                            
yoo         hat      yoo                  bar      hat                            
yooyooyooyo hathatha yooyooyooyooyooyooyo barbarba hathathathathathathathathatha 

Reference

http://stackoverflow.com/questions/5084743/how-to-print-pretty-string-output-in-python