コード例 #1
0
    def row_table(cls, d, order=None, labels=None):
        """
        prints a pretty table from data in the dict.

        :param d: A dict to be printed
        :param order: The order in which the columns are printed.
                      The order is specified by the key names of the dict.
        :param labels: The array of labels for the column
        """
        # header
        header = list(d)
        x = PrettyTable(labels)
        if order is None:
            order = header
        for key in order:
            value = d[key]
            if type(value) == list:
                x.add_row([key, value[0]])
                for element in value[1:]:
                    x.add_row(["", element])
            elif type(value) == dict:
                value_keys = list(value)
                first_key = value_keys[0]
                rest_keys = value_keys[1:]
                x.add_row(
                    [key, "{0} : {1}".format(first_key, value[first_key])])
                for element in rest_keys:
                    x.add_row(
                        ["", "{0} : {1}".format(element, value[element])])
            else:
                x.add_row([key, value])

        x.align = "l"
        return x
コード例 #2
0
    def attribute(cls,
                  d,
                  header=None,
                  order=None,
                  sort_keys=True,
                  humanize=None,
                  output="table"):
        """
        prints a attribute/key value table

        :param d: A a dict with dicts of the same type.
                  Each key will be a column
        :param order: The order in which the columns are printed.
                       The order is specified by the key names of the dict.
        :param header:  The Header of each of the columns
        :type header:   A list of string
        :param sort_keys:   Key(s) of the dict to be used for sorting.
                             This specify the column(s) in the table for sorting.
        :type sort_keys:    string or a tuple of string (for sorting with multiple columns)
        :param output: the output format table, csv, dict, json
        """

        if header is None:
            header = ["Attribute", "Value"]
        if output == "table":
            x = PrettyTable(header)
            if order is not None:
                sorted_list = order
            else:
                sorted_list = list(d)
            if sort_keys:
                sorted_list = sorted(d)

            for key in sorted_list:
                if type(d[key]) == dict:
                    values = d[key]
                    x.add_row([key, "+"])
                    for e in values:
                        x.add_row(["  -", "{}: {}".format(e, values[e])])
                elif type(d[key]) == list:
                    values = list(d[key])
                    x.add_row([key, "+"])
                    for e in values:
                        x.add_row(["  -", e])
                else:
                    x.add_row([key, d[key] or ""])

            x.align = "l"
            return x
        else:
            return cls.dict({output: d}, output=output)
コード例 #3
0
    def print_list(cls, l, output='table'):
        """
        prints a list
        :param l: the list
        :param output: the output, default is a table
        :return: 
        """

        def dict_from_list(l):
            """
            returns a dict from a list for printing
            :param l: the list
            :return: 
            """
            d = dict([(idx, item) for idx, item in enumerate(l)])
            return d

        if output == 'table':
            x = PrettyTable(["Index", "Host"])
            for (idx, item) in enumerate(l):
                x.add_row([idx, item])
            x.align = "l"
            x.align["Index"] = "r"
            return x
        elif output == 'csv':
            return ",".join(l)
        elif output == 'dict':
            d = dict_from_list(l)
            return d
        elif output == 'json':
            d = dict_from_list(l)
            result = json.dumps(d, indent=4)
            return result
        elif output == 'yaml':
            d = dict_from_list(l)
            result = yaml.dump(d, default_flow_style=False)
            return result
        elif output == 'txt':
            return "\n".join(l)
コード例 #4
0
    def dict_table(cls,
                   d,
                   order=None,
                   header=None,
                   sort_keys=True,
                   show_none="",
                   humanize=None,
                   max_width=48):
        """
        prints a pretty table from an dict of dicts

        :param d: A a dict with dicts of the same type. Each key will be a column
        :param order: The order in which the columns are printed.
                      The order is specified by the key names of the dict.
        :param header: The Header of each of the columns
        :type header: A list of string
        :param sort_keys: Key(s) of the dict to be used for sorting.
                          This specify the column(s) in the table for sorting.
        :type sort_keys: string or a tuple of string (for sorting with multiple columns)
        :param show_none: prints None if True for None values
        :type show_none: string
        :param max_width: maximum width for a cell
        :type max_width: int
        """
        def _keys():
            all_keys = []
            for e in d:
                keys = d[e].keys()
                all_keys.extend(keys)
            return list(set(all_keys))

        # noinspection PyBroadException
        def _get(item, key):
            try:
                tmp = str(d[item][key])
                if tmp == "None":
                    tmp = show_none
                elif humanize and key in humanize:
                    tmp = parser.parse(tmp)
                    tmp = naturaltime(tmp)
            except:
                tmp = ' '
            return tmp

        if d is None or d == {}:
            return None

        if order is None:
            order = _keys()

        if header is None and order is not None:
            header = order
        elif header is None:
            header = _keys()

        x = PrettyTable(header)
        x.max_width = max_width

        if sort_keys:
            if type(sort_keys) is str:
                sorted_list = sorted(d, key=lambda x: d[x][sort_keys])
            elif type(sort_keys) == tuple:
                sorted_list = sorted(
                    d,
                    key=lambda x: tuple(
                        [d[x][sort_key] for sort_key in sort_keys]))
            else:
                sorted_list = d
        else:
            sorted_list = d

        for element in sorted_list:
            values = []
            for key in order:
                value = _get(element, key)
                values.append(value)
            x.add_row(values)
        x.align = "l"
        return x