当前位置: 首页>>代码示例>>Python>>正文


Python Texttable.set_cols_width方法代码示例

本文整理汇总了Python中texttable.Texttable.set_cols_width方法的典型用法代码示例。如果您正苦于以下问题:Python Texttable.set_cols_width方法的具体用法?Python Texttable.set_cols_width怎么用?Python Texttable.set_cols_width使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在texttable.Texttable的用法示例。


在下文中一共展示了Texttable.set_cols_width方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: do_list

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        printer.out("Getting entitlements list of the UForge :")
                        entList = self.api.Entitlements.Getall()
                        if entList is None:
                                printer.out("No entitlements found.", printer.OK)
                        else:
                                entList=generics_utils.order_list_object_by(entList.entitlements.entitlement, "name")
                                printer.out("Entitlement list for the UForge :")
                                table = Texttable(200)
                                table.set_cols_align(["l", "l"])
                                table.header(["Name", "Description"])
                                table.set_cols_width([30,60])
                                for item in entList:
                                        table.add_row([item.name, item.description])
                                print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
开发者ID:DimitriSCOLE,项目名称:uforge-cli,代码行数:28,代码来源:entitlement.py

示例2: get_hard_drive_list_table

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
    def get_hard_drive_list_table(self):
        """Return a table of hard drives"""
        # Manually set permissions asserted, as this function can
        # run high privilege calls, but doesn't not require
        # permission checking
        self._get_registered_object('auth').set_permission_asserted()

        # Create table and set headings
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('ID', 'Size', 'Type', 'Storage Backend', 'Virtual Machine'))
        table.set_cols_width((50, 15, 15, 50, 20))

        # Obtain hard ives and add to table
        for hard_drive_obj in self.get_all():
            vm_object = hard_drive_obj.get_virtual_machine()
            hdd_type = ''
            storage_backend_id = 'Storage backend does not exist'
            try:
                storage_backend_id = hard_drive_obj.storage_backend.id_
                hdd_type = hard_drive_obj.get_type()
                hdd_size = SizeConverter(hard_drive_obj.get_size()).to_string()
            except (VolumeDoesNotExistError,
                    HardDriveDoesNotExistException,
                    StorageBackendDoesNotExist), exc:
                hdd_size = str(exc)

            table.add_row((hard_drive_obj.id_, hdd_size,
                           hdd_type, storage_backend_id,
                           vm_object.get_name() if vm_object else 'Not attached'))
开发者ID:ITDevLtd,项目名称:MCVirt,代码行数:32,代码来源:factory.py

示例3: output_table_list

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
    def output_table_list(tables):
        terminal_size = get_terminal_size()[1]
        widths = []
        for tab in tables:
            for i in range(0, len(tab.columns)):
                current_width = len(tab.columns[i].label)
                if len(widths) < i + 1:
                    widths.insert(i, current_width)
                elif widths[i] < current_width:
                    widths[i] = current_width
                for row in tab.data:
                    current_width = len(resolve_cell(row, tab.columns[i].accessor))
                    if current_width > widths[i]:
                        widths[i] = current_width

        if sum(widths) != terminal_size:
            widths[-1] = terminal_size - sum(widths[:-1]) - len(widths) * 3

        for tab in tables:
            table = Texttable(max_width=terminal_size)
            table.set_cols_width(widths)
            table.set_deco(0)
            table.header([i.label for i in tab.columns])
            table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
            six.print_(table.draw() + "\n")
开发者ID:jatinder-kumar-calsoft,项目名称:middleware,代码行数:27,代码来源:ascii.py

示例4: output_table

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
    def output_table(tab):
        max_width = get_terminal_size()[1]
        table = Texttable(max_width=max_width)
        table.set_deco(0)
        table.header([i.label for i in tab.columns])
        widths = []
        number_columns = len(tab.columns)
        remaining_space = max_width
        # set maximum column width based on the amount of terminal space minus the 3 pixel borders
        max_col_width = (remaining_space - number_columns * 3) / number_columns
        for i in range(0, number_columns):
            current_width = len(tab.columns[i].label)
            tab_cols_acc = tab.columns[i].accessor
            max_row_width = max(
                    [len(str(resolve_cell(row, tab_cols_acc))) for row in tab.data ]
                    )
            current_width = max_row_width if max_row_width > current_width else current_width
            if current_width < max_col_width:
                widths.insert(i, current_width)
                # reclaim space not used
                remaining_columns = number_columns - i - 1
                remaining_space = remaining_space - current_width - 3
                if remaining_columns != 0:
                    max_col_width = (remaining_space - remaining_columns * 3)/ remaining_columns
            else:
                widths.insert(i, max_col_width)
                remaining_space = remaining_space - max_col_width - 3
        table.set_cols_width(widths)

        table.add_rows([[AsciiOutputFormatter.format_value(resolve_cell(row, i.accessor), i.vt) for i in tab.columns] for row in tab.data], False)
        print(table.draw())
开发者ID:williambr,项目名称:middleware,代码行数:33,代码来源:ascii.py

示例5: find_commands

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def find_commands(db, *filters):
    user_filter = '\s+'.join(filters)
    user_re = re.compile(user_filter)
    RE_CACHE[user_filter] = user_re

    query = '''
    SELECT hostname, timestamp, duration, user_string
    FROM commands
    WHERE timestamp > ? AND user_string REGEXP ?
    ORDER BY timestamp
    '''

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('l', 'r', 'r', 'l'))
    table.header(('host', 'date', 'duration', 'command'))

    host_width = 6
    max_command_width = 9
    now = time.time()
    for row in db.execute(query, (TIMESTAMP, user_filter)):
        host_width = max(host_width, len(row[0]))
        max_command_width = max(max_command_width, len(row[3]))
        table.add_row((
            row[0],
            format_time(row[1], now),
            format_duration(row[2]) if row[2] > 0 else '',
            highlight(row[3], user_re)))

    table.set_cols_width((host_width, 30, 10, max_command_width + 2))

    print table.draw()
开发者ID:minyoung,项目名称:dotfiles,代码行数:34,代码来源:find-commands.py

示例6: print_histogram

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
    def print_histogram(self, minimum=5, maximum=100, max_range=10):
        table = Texttable()
        table.set_deco(Texttable.HEADER)
        table.set_cols_align(('l', 'r', 'l'))
        table.set_cols_width((10, 3, maximum))
        table.header(('range', '#', ''))

        start = 0
        previous = 0
        current_sum = 0

        for value, count in sorted(self.histogram.items()):
            new_row = \
                    (value - start) > max_range or \
                    current_sum >= minimum or \
                    current_sum + count >= maximum
            if new_row:
                # passing **locals() is such a hax, don't do this
                table.add_row(self._format_histogram_row(**locals()))
                start = value
                previous = value
                current_sum = count
            else:
                previous = value
                current_sum += count

        # passing **locals() is such a hax, don't do this
        table.add_row(self._format_histogram_row(**locals()))
        print table.draw()
开发者ID:minyoung,项目名称:dotfiles,代码行数:31,代码来源:count-vim-letters.py

示例7: containers_to_ascii_table

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def containers_to_ascii_table(containers):
    """Just a method that formats the images to ascii table.
    Expects dictionary {host: [images]}
    and prints multiple tables
    """
    with closing(StringIO()) as out:
        for host, values in containers.iteritems():
            out.write("[" + str(host) + "] \n")
            t = TextTable(max_width=400)
            t.set_deco(TextTable.HEADER)
            t.set_cols_dtype(['t'] * 6)
            t.set_cols_align(["l"] * 6)
            t.set_cols_width([12, 25, 25, 15, 20, 15])
            rows = []
            rows.append(
                ['Id', 'Image', 'Command', 'Created', 'Status', 'Ports'])
            for container in values:
                rows.append([
                    container.id[:12],
                    container.image,
                    container.command[:20],
                    time_ago(container.created),
                    container.status,
                    container.ports
                ])
            t.add_rows(rows)
            out.write(t.draw() + "\n\n")
        return out.getvalue()
开发者ID:carriercomm,项目名称:shipper,代码行数:30,代码来源:pretty.py

示例8: run

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def run(host, port):

    port = int(port)

    from . import interop_tests
    test_names = [x for x in dir(interop_tests) if x.startswith("test_")]

    tests = [getattr(interop_tests, test_name) for test_name in test_names]

    results = []
    with click.progressbar(tests, label="Running interop tests...") as _tests:
        for test in _tests:
            results.append(test(host, port))

    fmt_results = []
    for r in results:
        fmt_results.append((r.name,
                            "True" if r.success else "False", r.reason if r.reason else "", r.transcript))

    t = Texttable()
    t.set_cols_width([20, 10, 80, 60])
    rows = [["Name", "Successful", "Reason", "Client Transcript"]]
    rows.extend(fmt_results)
    t.add_rows(rows)
    print(t.draw(), file=sys.__stdout__)

    failures = []
    for x in results:
        if not x.success:
            failures.append(False)

    if failures:
        sys.exit(len(failures))
    sys.exit(0)
开发者ID:NinjaMSP,项目名称:crossbar,代码行数:36,代码来源:interop.py

示例9: sub

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def sub(db, command, *filters):
    counts = collections.defaultdict(int)
    user_filter = ' '.join(itertools.chain([command], filters))
    total = 0

    query = '''
    SELECT user_string
    FROM commands
    WHERE
        timestamp > ?
        AND command = ?
    '''

    for row in db.execute(query, (TIMESTAMP, command)):
        command = normalize_user_string(row[0])
        if command.startswith(user_filter):
            counts[command] += 1
            total += 1
    percentage = 100 / float(total)

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('r', 'r', 'l'))
    table.set_cols_width((5, 6, 75))
    table.header(('count', '%', 'command'))
    for key, value in sorted(counts.iteritems(), key=lambda (k, v): (v, k), reverse=True)[:20]:
        table.add_row((value, value * percentage, key))
    print table.draw()
开发者ID:minyoung,项目名称:dotfiles,代码行数:30,代码来源:top-commands.py

示例10: print_steps

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
    def print_steps(self, show_result=True):
        def max_len_of_list_of_str(s):
            return max(len(line) for line in str(s).split('\n'))

        def autodetect_width(d):
            widths = [0] * len(d[0])
            for line in d:
                for _i in range(len(line)):
                    widths[_i] = max(widths[_i], max_len_of_list_of_str(line[_i]))
            return widths

        if self.save_history:
            if self.errors:
                self.history = self.history[:-1]
            t = Texttable()
            header = ['№', 'Term', 'Code'] if self.parallel else ['№', 'Term', 'Code', 'Stack']
            data = [header] + [
                [repr(i) for i in item][:-1] if self.parallel else [repr(i) for i in item] for item in self.history]
            t.add_rows(data)
            t.set_cols_align(['l'] + ['r'] * (len(header) - 1))
            t.set_cols_valign(['m'] + ['m'] * (len(header) - 1))
            t.set_cols_width(autodetect_width(data))
            print t.draw()
        else:
            if not self.errors:
                print ' Steps: %10s' % self.iteration
                if show_result:
                    print 'Result: %10s' % repr(self.term)
开发者ID:MrBadge,项目名称:CAM-interpreter,代码行数:30,代码来源:core.py

示例11: list

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def list ():
  api.getCredentials()
  log.debug ("Command: List.")

  url = "/gists"
  gists = api.get(url)
  public_count = 0
  private_count = 0

  table = Texttable(max_width=defaults.max_width)
  table.set_deco(Texttable.HEADER | Texttable.HLINES)
  table.set_cols_align(["l", "l", "l", "l", "l"])
  table.set_cols_width([4, 30, 6, 20, 30])

  table.header( ["","Files","Public", "Gist ID",  "Description"] )

  for (i, gist) in enumerate(gists):
    private = False
    file_list = ''
    for (file, data) in gist['files'].items():
      file_list += "'" + file + "' " 
    if gist['public']:
      public_count += 1
    else:
      private_count += 1
    table.add_row( [i+1, file_list, str(gist['public']), gist['id'], gist['description']] )

  print table.draw()

  print ''
  print "You have %i Gists. (%i Private)" % (len(gists), private_count)
开发者ID:khilnani,项目名称:gists.cli,代码行数:33,代码来源:actions.py

示例12: do_list_changesets

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
 def do_list_changesets(self, arg, opts=None):
     """Show changesets needing review."""
     changesets = requests.get(
         "http://%s/api/v1/changeset/" % self.site, params={"review_status": "needs"}, auth=self.api_auth
     )
     objects = changesets.json().get("objects")
     table = Texttable()
     table.set_deco(Texttable.HEADER)
     table.set_cols_align(["c", "c", "c", "c", "c"])
     table.set_cols_width([5, 20, 15, 15, 10])
     rows = [["ID", "Type", "Classification", "Version Control URL", "Submitted By"]]
     for cs in objects:
         user = requests.get("http://%s%s" % (self.site, cs.get("submitted_by")), auth=self.api_auth)
         user_detail = user.json()
         rows.append(
             [
                 cs.get("id"),
                 cs.get("type"),
                 cs.get("classification"),
                 cs.get("version_control_url"),
                 user_detail.get("name"),
             ]
         )
     table.add_rows(rows)
     print "Changesets That Need To Be Reviewed:"
     print table.draw()
开发者ID:killkill,项目名称:schemanizer,代码行数:28,代码来源:signin.py

示例13: show_librations

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def show_librations(asteroid_condition: AsteroidCondition = None,
                    planet_condtion: PlanetCondition = None,
                    is_pure: bool = None, is_apocentric: bool = None,
                    axis_interval: AxisInterval = None, integers: List[str] = None,
                    body_count=3, limit=100, offset=0):
    body_count = BodyNumberEnum(body_count)
    is_three = (body_count == BodyNumberEnum.three)
    query = _build_libration_query(asteroid_condition, planet_condtion, is_pure, is_apocentric,
                                   axis_interval, integers, body_count, limit, offset)
    table = Texttable(max_width=120)
    witdths = [10] * body_count.value
    table.set_cols_width(witdths + [30, 15, 10, 10])
    headers = ['First planet']
    if is_three:
        headers.append('Second planet')
    headers += ['Asteroid', 'Integers and semi major axis of asteroid', 'apocentric', 'pure',
                'axis (degrees)']
    table.add_row(headers)

    for resonance in query:  # type: ResonanceMixin
        libration = resonance.libration
        data = [x.name for x in resonance.get_big_bodies()]
        data += [
            resonance.small_body.name,
            resonance,
            '%sapocentric' % ('not ' if not libration.is_apocentric else ''),
            '%spure' % ('not ' if not libration.is_pure else ''),
            resonance.asteroid_axis
        ]
        table.add_row(data)

    print(table.draw())
开发者ID:4xxi,项目名称:resonances,代码行数:34,代码来源:librations.py

示例14: _dataframe_to_texttable

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def _dataframe_to_texttable(df, align=None):
    """Convert data frame to texttable. Sets column widths to the
    widest entry in each column."""
    ttab = Texttable()
    ttab.set_precision(1)
    h = [[x for x in df]]
    h.extend([x for x in df.to_records(index=False)])
    if align:
        colWidths = [max(len(x), len(".. class:: {}".format(y))) for x,y in izip(df.columns, align)]
    else:
        colWidths = [len(x) for x in df.columns]
    for row in h:
        for i in range(0, len(row)):
            if type(row[i]) == str:
                colWidths[i] = max([len(str(x)) for x in row[i].split("\n")] + [colWidths[i]])
            colWidths[i] = max(len(str(row[i])), colWidths[i])
    table_data = []
    if align:
        for row in h:
            table_row = []
            i = 0
            for col, aln in izip(row, align):
                table_row.append(".. class:: {}".format(aln) + " " * colWidths[i] + "{}".format(col))
                i = i + 1
            table_data.append(table_row)
    else:
        table_data = h
    ttab.add_rows(table_data)
    ttab.set_cols_width(colWidths)
    # Note: this does not affect the final pdf output
    ttab.set_cols_align(["r"] * len(colWidths))
    return ttab
开发者ID:Galithil,项目名称:scilifelab,代码行数:34,代码来源:best_practice.py

示例15: format_info

# 需要导入模块: from texttable import Texttable [as 别名]
# 或者: from texttable.Texttable import set_cols_width [as 别名]
def format_info(value, format, cols_width=None, dumper=None):
    if format in(INFO_FORMAT.DICT, INFO_FORMAT.JSON, INFO_FORMAT.YAML):
        value['component_details'] = json_loads(value['component_details'])

    if format == INFO_FORMAT.JSON:
        return json_dumps(value)

    elif format == INFO_FORMAT.YAML:
        buff = StringIO()
        yaml.dump_all([value], default_flow_style=False, indent=4, Dumper=dumper, stream=buff)
        value = buff.getvalue()
        buff.close()

        return value

    elif format == INFO_FORMAT.TEXT:
        cols_width = (elem.strip() for elem in cols_width.split(','))
        cols_width = [int(elem) for elem in cols_width]

        table = Texttable()
        table.set_cols_width(cols_width)

        # Use text ('t') instead of auto so that boolean values don't get converted into ints
        table.set_cols_dtype(['t', 't'])

        rows = [['Key', 'Value']]
        rows.extend(sorted(value.items()))

        table.add_rows(rows)

        return table.draw()

    else:
        return value
开发者ID:Aayush-Kasurde,项目名称:zato,代码行数:36,代码来源:component_info.py


注:本文中的texttable.Texttable.set_cols_width方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。