Python terminaltables.SingleTable() Examples

The following are 30 code examples of terminaltables.SingleTable(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module terminaltables , or try the search function .
Example #1
Source File: buildman.py    From boss with MIT License 7 votes vote down vote up
def display_list(history):
    ''' Display build history. '''
    if not history['builds']:
        remote_info('No builds have been deployed yet.')
        return

    remote_info('Showing recent builds')

    # Map build data into tabular format
    data = map(row_mapper_wrt(history['current']), history['builds'])

    # Prepend heading rows
    data.insert(0, [
        ' ', 'ID', 'Commit',
        'Branch', 'Created By', 'Timestamp'
    ])

    table = SingleTable(data)
    print('')
    print(table.table) 
Example #2
Source File: buildman.py    From boss with MIT License 7 votes vote down vote up
def display(id):
    ''' Display build information by build id. '''
    history = load_history()
    build = get_build_info(history, id or history['current'])
    is_current = build['id'] == history['current']
    timestamp = local_timestamp(build['timestamp'])

    table = SingleTable([
        [green('Build ' + build['id'])],
        ['ID: ' + green(build['id'])],
        ['Commit: ' + green(build['commit'])],
        ['Branch: ' + green(build['branch'])],
        ['Stage: ' + green(build['stage'])],
        ['Created By: ' + green(build['createdBy'])],
        ['Path: ' + green(build['path'])],
        ['Current Build: ' + green('Yes' if is_current else 'No')],
        ['Timestamp: ' + green(timestamp)]
    ])
    print(table.table) 
Example #3
Source File: std.py    From sqliv with GNU General Public License v3.0 6 votes vote down vote up
def normalprint(data):
    """show vulnerable websites in table"""

    # [
    #   ["index", "url"],
    #   ["1", "sql.com"]
    # ]

    title = " VULNERABLE URLS "
    table_data = [["index", "url", "db"]]
    # add into table_data by one by one
    for index, url in enumerate(data):
        table_data.append([index+1, url[0], url[1]])

    table = SingleTable(table_data, title)
    print(table.table) 
Example #4
Source File: commands.py    From rpl-attacks with GNU Affero General Public License v3.0 6 votes vote down vote up
def list(item_type, **kwargs):
    """
    List all available items of a specified type.

    :param item_type: experiment/campaign/wsn-generation-algorithm
    :param kwargs: simulation keyword arguments (see the documentation for more information)
    """
    data, title = [['Name']], None
    if item_type == 'experiments':
        title = 'Available experiments'
        data.extend([['- {}'.format(x).ljust(25)] for x in list_experiments()])
    elif item_type == 'campaigns':
        title = 'Available campaigns'
        data.extend([['- {}'.format(x).ljust(25)] for x in list_campaigns()])
    elif item_type == 'wsn-generation-algorithms':
        title = 'Available WSN generation algorithms'
        data.extend([['- {}'.format(x).ljust(25)] for x in list_wsn_gen_algorithms()])
    if title is not None:
        table = SingleTable(data, title)
        print(table.table)


# ***************************************** SETUP COMMANDS **************************************** 
Example #5
Source File: console.py    From rpl-attacks with GNU Affero General Public License v3.0 6 votes vote down vote up
def do_status(self, line):
        """
    Display process pool status.
        """
        self.clean_tasks()
        # this prevents from re-displaying the same status table once ENTER is pressed
        #  (marker 'restart' is handled in emptyline() hereafter
        if line == 'restart' and self.__last_tasklist is not None and \
                        hash(repr(self.tasklist)) == self.__last_tasklist:
            return
        self.__last_tasklist = hash(repr(copy(self.tasklist)))
        if len(self.tasklist) == 0:
            data = [['No task currently running']]
        else:
            data = [['Task', 'Status', 'Result']]
            for task, info in sorted(self.tasklist.items(), key=lambda x: str(x[0])):
                data.append([str(task).ljust(15), info['status'].ljust(10), str(info['result']).ljust(40)])
        table = SingleTable(data, 'Status of opened tasks')
        table.justify_columns = {0: 'center', 1: 'center', 2: 'center'}
        print(table.table) 
Example #6
Source File: ui.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, data, title=None, wrap_cols=None, bool_cols=None, dim_rows=None):
        """Constructor.
        Args:
            data: Required. List[List] of data to format, with the heading as 0-th member.
            title: String to use as the table's title.
            wrap_cols: List[str] of column names to wrap to max width.
            bool_cols: List[str] of columns containing booleans to stringify.
            dim_rows: List[int] of row indices to dim.
        """
        self._data = data
        self._header = data[0]
        self._title = title
        self._table = SingleTable(self._data, self._title)

        if wrap_cols:
            self._table_wrapper(self._table, wrap_cols)
        if bool_cols:
            for name in bool_cols:
                self.stringify_boolean_col(col_name=name)
        if dim_rows:
            self._dim_row_list(dim_rows) 
Example #7
Source File: example2.py    From terminaltables with MIT License 6 votes vote down vote up
def main():
    """Main function."""
    Windows.enable(auto_colors=True, reset_atexit=True)  # Does nothing if not on Windows.

    # Server timings.
    print(table_server_timings())
    print()

    # Server status.
    print(table_server_status())
    print()

    # Two A B C D tables.
    print(table_abcd())
    print()

    # Instructions.
    table_instance = SingleTable([['Obey Obey Obey Obey']], 'Instructions')
    print(table_instance.table)
    print() 
Example #8
Source File: example2.py    From terminaltables with MIT License 6 votes vote down vote up
def table_abcd():
    """Return table string to be printed. Two tables on one line."""
    table_instance = SingleTable([['A', 'B'], ['C', 'D']])

    # Get first table lines.
    table_instance.outer_border = False
    table_inner_borders = table_instance.table.splitlines()

    # Get second table lines.
    table_instance.outer_border = True
    table_instance.inner_heading_row_border = False
    table_instance.inner_column_border = False
    table_outer_borders = table_instance.table.splitlines()

    # Combine.
    smallest, largest = sorted([table_inner_borders, table_outer_borders], key=len)
    smallest += [''] * (len(largest) - len(smallest))  # Make both same size.
    combined = list()
    for i, row in enumerate(largest):
        combined.append(row.ljust(10) + '          ' + smallest[i])
    return '\n'.join(combined) 
Example #9
Source File: output.py    From linode-cli with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _table_output(self, header, data, columns, title, to):
        """
        Pretty-prints data in a table
        """
        content = []

        if isinstance(columns[0], str):
            content=data
        else:
            for model in data:
                content.append([attr.render_value(model) for attr in columns])

        if self.headers:
            content = [header]+content

        tab = SingleTable(content)

        if title is not None:
            tab.title=title

        if not self.headers:
            tab.inner_heading_row_border = False

        print(tab.table, file=to) 
Example #10
Source File: example1.py    From terminaltables with MIT License 6 votes vote down vote up
def main():
    """Main function."""
    title = 'Jetta SportWagen'

    # AsciiTable.
    table_instance = AsciiTable(TABLE_DATA, title)
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print()

    # SingleTable.
    table_instance = SingleTable(TABLE_DATA, title)
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print()

    # DoubleTable.
    table_instance = DoubleTable(TABLE_DATA, title)
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print() 
Example #11
Source File: client.py    From python-emv with MIT License 6 votes vote down vote up
def appdata(ctx, app_index):
    redact = ctx.obj["redact"]
    card = get_reader(ctx.obj["reader"])
    apps = card.list_applications()
    app = apps[app_index]
    card.select_application(app[Tag.ADF_NAME])
    click.secho(
        "Selected application %s (%s)"
        % (
            render_element(Tag.APP_LABEL, app[Tag.APP_LABEL]),
            render_element(Tag.ADF_NAME, app[Tag.ADF_NAME]),
        ),
        bold=True,
    )
    opts = card.get_processing_options()

    res = [["Key", "Value"]]
    for k, v in opts.items():
        res.append((k, v))
    table = SingleTable(res)
    table.title = "Processing Options"
    click.echo(table.table)

    app_data = card.get_application_data(opts["AFL"])
    click.echo(as_table(app_data, title="Application Data", redact=redact)) 
Example #12
Source File: client.py    From python-emv with MIT License 6 votes vote down vote up
def listapps(ctx):
    card = get_reader(ctx.obj["reader"])
    apps = card.list_applications()
    res = [["Index", "Label", "ADF"]]
    i = 0
    for app in apps:
        res.append(
            [
                i,
                render_element(Tag.APP_LABEL, app[Tag.APP_LABEL]),
                render_element(Tag.ADF_NAME, app[Tag.ADF_NAME]),
            ]
        )
        i += 1

    table = SingleTable(res)
    table.title = "Applications"
    click.echo(table.table) 
Example #13
Source File: std.py    From sqliv with GNU General Public License v3.0 6 votes vote down vote up
def fullprint(data):
    """show vulnerable websites in table with server info"""

    # [
    #   ["index", "url", "db", server", "lang"],
    #   ["1", "sql.com", "mysql", apache", "php/5.5xxx"]
    # ]

    title = " VULNERABLE URLS "
    table_data = [["index", "url", "db", "server", "lang"]]
    # add into table_data by one by one
    for index, each in enumerate(data):
        table_data.append([index+1, each[0], each[1], each[2][0:30], each[3][0:30]])

    table = SingleTable(table_data, title)
    print(table.table) 
Example #14
Source File: std.py    From sqliv with GNU General Public License v3.0 6 votes vote down vote up
def printserverinfo(data):
    """show vulnerable websites in table"""

    # [
    #   ["website", "server", "lang"],
    #   [sql.com", "apache", "php/5.5xxxx"]
    # ]

    # check if table column and data columns are the same
    if not all(isinstance(item, list) for item in data):
        stderr("program err, data must be two dimentional array")
        return

    title = " DOMAINS "
    table_data = [["website", "server", "lang"]] + data

    table = SingleTable(table_data, title)
    print(table.table) 
Example #15
Source File: client.py    From python-emv with MIT License 6 votes vote down vote up
def as_table(tlv, title=None, redact=False):
    res = [["Tag", "Name", "Value"]]
    if type(tlv) is not TLV:
        return ""
    for tag, value in tlv.items():
        res.append(
            [
                format_bytes(tag.id),
                tag.name or "",
                "\n".join(textwrap.wrap(render_element(tag, value, redact=redact), 80)),
            ]
        )
    table = SingleTable(res)
    if title is not None:
        table.title = title
    return table.table 
Example #16
Source File: logging_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def print_table(TABLE_DATA):

    table_instance = SingleTable(TABLE_DATA, "")
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print 
Example #17
Source File: obj.py    From linode-cli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _borderless_table(data):
    """
    Returns a terminaltables.SingleTable object with no borders and correct padding
    """
    tab = SingleTable(data)
    tab.inner_heading_row_border = False
    tab.inner_column_border = False
    tab.outer_border = False
    tab.padding_left=0
    tab.padding_right=2

    return tab 
Example #18
Source File: shell.py    From RobinhoodShell with MIT License 5 votes vote down vote up
def do_w(self, arg):
        'Show watchlist w \nAdd to watchlist w a <symbol> \nRemove from watchlist w r <symbols>'
        parts = re.split('\W+',arg.upper())

        if len(parts) >= 2:
            if parts[0] == 'A':
                for p in parts[1:]:
                    if p not in self.watchlist:
                        self.watchlist.append(p.strip())
            if parts[0] == 'R':
                self.watchlist = [r for r in self.watchlist if r not in parts[1:]]
            print("Done")
        else:
            watch_t_data=[]
            watch_table = SingleTable(watch_t_data,'Watch List')
            watch_table.inner_row_border = True
            watch_table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3:'center',4: 'center'}
            watch_t_data.append(["Symbol","Ask Price", "Open", "Today", "%"])

            if len(self.watchlist) > 0:
                instruments = [self.get_instrument(s)['url'] for s in
                        self.watchlist]
                raw_data = self.trader.get_stock_marketdata(instruments)
                quotes_data = {}
                for quote in raw_data:
                    day_change = float(quote['last_trade_price']) - float(quote['previous_close'])
                    day_change_pct = '{:05.2f}'.format(( day_change / float(quote['previous_close']) ) * 100)
                    watch_t_data.append([
                        quote['symbol'],
                        '{:05.2f}'.format(float(quote['last_trade_price'])),
                        '{:05.2f}'.format(float(quote['previous_close'])),
                        color_data(day_change),
                        color_data(day_change_pct)
                        ])
                print((watch_table.table))
            else:
                print("Watchlist empty!") 
Example #19
Source File: logging_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def print_table(TABLE_DATA):

    table_instance = SingleTable(TABLE_DATA, "")
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print 
Example #20
Source File: shell.py    From RobinhoodShell with MIT License 5 votes vote down vote up
def do_o(self, arg):
        'List open orders'
        open_orders = self.trader.get_open_orders()
        if open_orders:
            open_t_data=[]
            open_table = SingleTable(open_t_data,'open List')
            open_table.inner_row_border = True
            open_table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3:'center',4: 'center'}
            open_t_data.append( ["index", "symbol", "price", "quantity", "type", "id"])

            index = 1
            for order in open_orders:

                if order['trigger'] == 'stop':
                    order_price = order['stop_price']
                    order_type  = "stop loss"
                else:
                    order_price = order['price']
                    order_type  = order['side']+" "+order['type']

                open_t_data.append([
                    index,
                    self.get_symbol(order['instrument']),
                    order_price,
                    int(float(order['quantity'])),
                    order_type,
                    order['id'],
                ])
                index += 1

            print((open_table.table))
        else:
            print("No Open Orders") 
Example #21
Source File: shell.py    From RobinhoodShell with MIT License 5 votes vote down vote up
def do_q(self, arg):
        'Get detailed quote for stock: q <symbol(s)>'

        symbols = re.split('\W+',arg.upper())

        if len(arg) == 0:
            print("Missing symbol(s)")
        else:
            instruments = [self.get_instrument(s)['url'] for s in symbols]
            raw_data = self.trader.get_stock_marketdata(instruments)
            quotes_data = {}
            quote_t_data=[]
            quote_table = SingleTable(quote_t_data,'Quote List')
            quote_table.inner_row_border = True
            quote_table.justify_columns = {0: 'center', 1: 'center', 2: 'center', 3:'center',4: 'center'}
            quote_t_data.append(["Symbol", "Current Price", "Open","Change", "Ask","Bid"])
            for quote in raw_data:
                if not quote:
                    continue
                day_change = float(quote['last_trade_price']) - float(quote['previous_close'])
                day_change_pct = ( day_change / float(quote['previous_close']) ) * 100
                ask_price = '{:05.2f}'.format(float(quote['ask_price']))
                ask_size = quote['ask_size']
                bid_price = '{:05.2f}'.format(float(quote['bid_price']))
                bid_size  = quote['bid_size']
                quote_t_data.append([
                    quote['symbol'],
                    '{:05.2f}'.format(float(quote['last_trade_price'])),
                    '{:05.2f}'.format(float(quote['previous_close'])),
                    color_data(day_change)+' ('+color_data('{:05.2f}'.format(day_change_pct))+'%)',
                    str(ask_price)+' x '+str(ask_size),
                    str(bid_price)+' x '+str(bid_size)
                    ])
            print((quote_table.table)) 
Example #22
Source File: logging_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def print_table(TABLE_DATA):

    table_instance = SingleTable(TABLE_DATA, "")
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print 
Example #23
Source File: shell.py    From RobinhoodShell with MIT License 5 votes vote down vote up
def do_qq(self, arg):
        'Get quote for stock q <symbol> or option q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd>'
        arg = arg.strip().split()
        try:
            symbol = arg[0].upper()
        except:
            print("Please check arguments again. Format: ")
            print("Stock: q <symbol>")
            print("Option: q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd>")
        type = strike = expiry = None
        if len(arg) > 1:
            try:
                type = arg[1]
                strike = arg[2]
            except Exception as e:
                print("Please check arguments again. Format: ")
                print("q <symbol> <call/put> <strike> <(optional) YYYY-mm-dd>")

            try:
                expiry = arg[3]
            except:
                expiry = None

            arg_dict = {'symbol': symbol, 'type': type, 'expiration_dates': expiry, 'strike_price': strike, 'state': 'active', 'tradability': 'tradable'};
            quotes = self.trader.get_option_quote(arg_dict);

            qquote_t_data=[]
            qquote_table = SingleTable(qquote_t_data,'Quote List')
            qquote_table.inner_row_border = True
            qquote_table.justify_columns = {0: 'center', 1: 'center'}
            qquote_t_data.append(['expiry', 'price'])

            for row in quotes:
                qquote_t_data.append(row)

            print((qquote_table.table))
        else:
            try:
                self.trader.print_quote(symbol)
            except:
                print("Error getting quote for:", symbol) 
Example #24
Source File: logging_utils.py    From DeepLearningImplementations with MIT License 5 votes vote down vote up
def print_table(TABLE_DATA):

    table_instance = SingleTable(TABLE_DATA, "")
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print 
Example #25
Source File: main_menu.py    From evillimiter with MIT License 5 votes vote down vote up
def _hosts_handler(self, args):
        """
        Handles 'hosts' command-line argument
        Displays discovered hosts
        """
        table_data = [[
            '{}ID{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
            '{}IP address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
            '{}MAC address{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
            '{}Hostname{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL),
            '{}Status{}'.format(IO.Style.BRIGHT, IO.Style.RESET_ALL)
        ]]
        
        with self.hosts_lock:
            for host in self.hosts:
                table_data.append([
                    '{}{}{}'.format(IO.Fore.LIGHTYELLOW_EX, self._get_host_id(host, lock=False), IO.Style.RESET_ALL),
                    host.ip,
                    host.mac,
                    host.name,
                    host.pretty_status()
                ])

        table = SingleTable(table_data, 'Hosts')

        if not args.force and not table.ok:
            IO.error('table does not fit terminal. resize or decrease font size. you can also force the display (--force).')
            return

        IO.spacer()
        IO.print(table.table)
        IO.spacer() 
Example #26
Source File: strings.py    From Kathara with GNU General Public License v3.0 5 votes vote down vote up
def formatted_strings():
    commands = []
    for item in strings.items():
        commands.append(list(item))

    commands_table = SingleTable(commands)
    commands_table.inner_heading_row_border = False
    commands_table.outer_border = False
    commands_table.inner_column_border = False

    return commands_table.table 
Example #27
Source File: tabular.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _render_pretty(self, data):
        rows = self._compute_rows(RenderTarget.pretty, data)
        rows.insert(
            0, [column.title for column in self._flatten_columns(self.visible_columns)]
        )
        return terminaltables.SingleTable(rows).table 
Example #28
Source File: tabular.py    From python-libmaas with GNU Affero General Public License v3.0 5 votes vote down vote up
def _render_pretty(self, data):
        return self._render_table(RenderTarget.pretty, terminaltables.SingleTable, data) 
Example #29
Source File: cmdline_printer.py    From homer with MIT License 5 votes vote down vote up
def print_paragraph_stats(self):
        """This method, along with print_article_stats(), can be called to present paragraph stats on a command line.
        Ideally first call print_article_stats() and then this method.
        It shows sentence, average words per sentence, longest sentence, and readability scores (Flesch reading ease and
        Dale Chall readability scores) of paragraphs.
        """

        sentence_tag = Color('{blue}sentences{/blue}')
        word_tag = Color('{blue}words{/blue}')
        avg_word_tag = Color('{blue}Avg words per sentence{/blue}')
        long_tag = Color('{red}longest{/red}')
        table_data = [
            [Color('{autocyan}Paragraph Stats{/autocyan}')],
            ['Paragraph #', '']
        ]
        for item, para in enumerate(self.article.paragraphs):
            sentences = Color('{red}%s{/red}' % str(len(para))) if len(para) > 5 else str(len(para))
            avg_words_per_sentence = Color(
                '{red}%s{/red}' % str(para.avg_words_per_sentence)) if para.avg_words_per_sentence > 25 else str(
                para.avg_words_per_sentence)
            table_data.append([item + 1,
                               '{sentences} {sent_tag}. {words} {word_tag}. {avg_words} {avg_word_tag}. '
                               '"{longest_sent}..." is the {long_tag} sentence.'.format(
                                   sentences=sentences, sent_tag=sentence_tag, words=para.total_words,
                                   word_tag=word_tag, avg_words=avg_words_per_sentence, avg_word_tag=avg_word_tag,
                                   longest_sent=str(para.longest_sentence)[0:10], long_tag=long_tag
                               )])
            table_data.append(["", "Flesh Reading score={flesch_reading}, Dale Chall Readability= {dale_chall}".format(
                flesch_reading=para.get_flesch_reading_score(), dale_chall=para.get_dale_chall_reading_score()
            )])

        table_instance = SingleTable(table_data)
        table_instance.inner_heading_row_border = True
        table_instance.inner_row_border = True
        table_instance.justify_columns = {0: 'center', 1: 'left'}
        print(table_instance.table) 
Example #30
Source File: cmdline_printer.py    From homer with MIT License 5 votes vote down vote up
def print_article_stats(self):
        """This method is called to present overall article stats on a command line."""
        table_data = [
            [Color('{autocyan}Overall Stats{/autocyan}')],
            ['Reading time', str(self.article.reading_time) + ' mins'],
            ['Flesch Reading Ease', self.article.get_flesch_reading_score()],
            ['Dale Chall Readability Score', self.article.get_dale_chall_reading_score()],
            ['Paragraphs', self.article.total_paragraphs],
            ['Avg sentences per paragraph', self.article.avg_sentences_per_para],
            ['Total sentences in longest paragraph', self.article.len_of_longest_paragraph],
            ['Sentences', self.article.total_sentences],
            ['Avg words per sentence', self.article.avg_words_per_sentence],
            ['Longest sentence', "%s..." % str(self.article.longest_sentence)[0:30]],
            ['Words in longest sentence', self.article.len_of_longest_sentence],
            ['Words', self.article.total_words],
            ['"and" frequency"', self.article.get_and_frequency()],
            ['Compulsive Hedgers', len(self.article.get_compulsive_hedgers())],
            ['Intensifiers', len(self.article.get_intensifiers())],
            ['Vague words', len(self.article.get_vague_words())],
        ]
        table_instance = SingleTable(table_data)
        table_instance.inner_heading_row_border = True
        table_instance.inner_row_border = True
        table_instance.justify_columns = {0: 'left', 1: 'center'}
        print(table_instance.table)
        self.print_detail()