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


Python textwrap.indent方法代码示例

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


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

示例1: str

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def str(self, highlight=False) -> str:
        s = ''
        if self.name:
            s = sformat(self.name, sformat.blue, apply=highlight) + ': '

        suffix = sformat(
            ' ({.value.__class__.__name__}){}'.format(self, ''.join(' {}={}'.format(k, v) for k, v in self.extra)),
            sformat.dim,
            apply=highlight,
        )
        try:
            s += pformat(self.value, indent=4, highlight=highlight)
        except Exception as exc:
            s += '{!r}{}\n    {}'.format(
                self.value,
                suffix,
                sformat('!!! error pretty printing value: {!r}'.format(exc), sformat.yellow, apply=highlight),
            )
        else:
            s += suffix
        return s 
开发者ID:samuelcolvin,项目名称:python-devtools,代码行数:23,代码来源:debug.py

示例2: status

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def status(self, workspacePath):
        status = ScmStatus()
        try:
            output = self.callSubversion(workspacePath, 'status')
            if output:
                status.add(ScmTaint.modified, joinLines("> modified:", indent(output, '   ')))

            output = self.callSubversion(workspacePath, 'info', '--xml')
            info = ElementTree.fromstring(output)
            entry = info.find('entry')
            url = entry.find('url').text
            revision = entry.attrib['revision']

            if self.__url != url:
                status.add(ScmTaint.switched,
                    "> URL: configured: '{}', actual: '{}'".format(self.__url, url))
            if self.__revision is not None and int(revision) != int(self.__revision):
                status.add(ScmTaint.switched,
                    "> revision: configured: {}, actual: {}".format(self.__revision, revision))

        except BuildError as e:
            status.add(ScmTaint.error, e.slogan)

        return status 
开发者ID:BobBuildTool,项目名称:bob,代码行数:26,代码来源:svn.py

示例3: describe_subtree

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def describe_subtree(self, ht, buffer, indent=0):
        """ Walk the tree and write its structure to a buffer string.

        Parameters
        ----------
        ht: HoeffdingTreeClassifier
            The tree to describe.
        buffer: string
            The buffer where the tree's structure will be stored.
        indent: int
            Indentation level (number of white spaces for current node).

        """
        for branch_idx in range(self.num_children()):
            child = self.get_child(branch_idx)
            if child is not None:
                buffer[0] += textwrap.indent('if ', ' ' * indent)
                buffer[0] += self._split_test.describe_condition_for_branch(branch_idx)
                buffer[0] += ':\n'
                child.describe_subtree(ht, buffer, indent + 2) 
开发者ID:scikit-multiflow,项目名称:scikit-multiflow,代码行数:22,代码来源:split_node.py

示例4: constraint_code

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def constraint_code(self, block: base.PLBlock) -> str:
        if isinstance(self.expr, base.Query):
            var = block.declare_var(self.expr.type)
            indent = len(var) + 5
            expr_text = textwrap.indent(self.expr.text, ' ' * indent).strip()
            block.add_command(f'{var} := ({expr_text})')

            code = f"'CHECK (' || {var} || ')'"
            if not self.inherit:
                code += " || ' NO INHERIT'"

            code = base.PLExpression(code)

        else:
            code = f'CHECK ({self.expr})'
            if not self.inherit:
                code += ' NO INHERIT'

        return code 
开发者ID:edgedb,项目名称:edgedb,代码行数:21,代码来源:tables.py

示例5: pformat

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def pformat(self) -> str:
        if self.children:
            child_formats = []
            for c in self.children:
                cf = c.pformat()
                if cf:
                    child_formats.append(cf)

            if child_formats:
                child_formats = sorted(child_formats)
                children = textwrap.indent(',\n'.join(child_formats), '    ')
                return f'"{self.name}": {{\n{children}\n}}'

        if self.path_id is not None:
            return f'"{self.name}"'
        else:
            return '' 
开发者ID:edgedb,项目名称:edgedb,代码行数:19,代码来源:scopetree.py

示例6: _anim_rst

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def _anim_rst(anim, image_path, gallery_conf):
    from matplotlib.animation import ImageMagickWriter
    # output the thumbnail as the image, as it will just be copied
    # if it's the file thumbnail
    fig = anim._fig
    image_path = image_path.replace('.png', '.gif')
    fig_size = fig.get_size_inches()
    thumb_size = gallery_conf['thumbnail_size']
    use_dpi = round(
        min(t_s / f_s for t_s, f_s in zip(thumb_size, fig_size)))
    # FFmpeg is buggy for GIFs
    if ImageMagickWriter.isAvailable():
        writer = 'imagemagick'
    else:
        writer = None
    anim.save(image_path, writer=writer, dpi=use_dpi)
    html = anim._repr_html_()
    if html is None:  # plt.rcParams['animation.html'] == 'none'
        html = anim.to_jshtml()
    html = indent(html, '         ')
    return _ANIMATION_RST.format(html) 
开发者ID:sphinx-gallery,项目名称:sphinx-gallery,代码行数:23,代码来源:scrapers.py

示例7: evaluate

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def evaluate(bot, body):
    env = {"bot": bot}
    env.update(globals())
    stdout = StringIO()
    to_compile = f'async def func():\n{textwrap.indent(body, "  ")}'
    try:
        exec(to_compile, env)
    except Exception as e:
        return f"```py\n{e.__class__.__name__}: {e}\n```"

    func = env["func"]
    try:
        with redirect_stdout(stdout):
            ret = await func()
    except Exception:
        value = stdout.getvalue()
        return f"```py\n{value}{format_exc()}\n```"
    else:
        value = stdout.getvalue()

        if ret is None:
            if value:
                return f"```py\n{value}\n```"
        else:
            return f"```py\n{value}{ret}\n```" 
开发者ID:CHamburr,项目名称:modmail,代码行数:27,代码来源:eval.py

示例8: indent

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def indent(lines, spaces=4):
    """Indent `lines` by `spaces` spaces.

    Parameters
    ----------
    lines : Union[str, List[str]]
        A string or list of strings to indent
    spaces : int
        The number of spaces to indent `lines`

    Returns
    -------
    indented_lines : str
    """
    if isinstance(lines, str):
        text = [lines]
    text = '\n'.join(lines)
    return textwrap.indent(text, ' ' * spaces) 
开发者ID:ibis-project,项目名称:ibis,代码行数:20,代码来源:core.py

示例9: _pprint_table

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def _pprint_table(table, leadingspace=2):
    """
    Given the list of list of strings, return a string of REST table format.
    """
    col_len = [max(len(cell) for cell in column) for column in zip(*table)]
    table_formatstr = '   '.join('=' * cl for cl in col_len)
    lines = [
        '',
        table_formatstr,
        '   '.join(cell.ljust(cl) for cell, cl in zip(table[0], col_len)),
        table_formatstr,
        *['   '.join(cell.ljust(cl) for cell, cl in zip(row, col_len))
          for row in table[1:]],
        table_formatstr,
        '',
    ]
    return textwrap.indent('\n'.join(lines), ' ' * leadingspace) 
开发者ID:PacktPublishing,项目名称:Mastering-Elasticsearch-7.0,代码行数:19,代码来源:patches.py

示例10: indent

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def indent(text, prefix, predicate=None):
    '''
    This is a direct copy of ``textwrap.indent`` for availability in Python 2.

    Their documentation:

    Adds 'prefix' to the beginning of selected lines in 'text'.
    If 'predicate' is provided, 'prefix' will only be added to the lines
    where 'predicate(line)' is True. If 'predicate' is not provided,
    it will default to adding 'prefix' to all non-empty lines that do not
    consist solely of whitespace characters.
    '''
    if predicate is None:
        def predicate(line):
            return line.strip()

    def prefixed_lines():
        for line in text.splitlines(True):
            yield (prefix + line if predicate(line) else line)

    return ''.join(prefixed_lines()) 
开发者ID:svenevs,项目名称:exhale,代码行数:23,代码来源:utils.py

示例11: prefix

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def prefix(token, msg):
    '''
    Wrapper call to :func:`~exhale.utils.indent` with an always-true predicate so that
    empty lines (e.g. `\\n`) still get indented by the ``token``.

    :Parameters:
        ``token`` (str)
            What to indent the message by (e.g. ``"(!) "``).

        ``msg`` (str)
            The message to get indented by ``token``.

    :Return:
        ``str``
            The message ``msg``, indented by the ``token``.
    '''
    return indent(msg, token, predicate=lambda x: True) 
开发者ID:svenevs,项目名称:exhale,代码行数:19,代码来源:utils.py

示例12: update

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def update(self, property_name, source_code_str):
        """Update the given property with the given source code.

        This does not write the results to file immediately, rather, this updates an internal buffer with the
        updated source code. To write to file use :meth:`write_to_file`.

        Args:
            property_name (str): the property (attribute or function) to update
            source_code_str (str): the updated source code for the property
        """
        try:
            start, end = self._fine_property_definition(property_name)
            source_lines = self._source.split('\n')
            new_source = '\n'.join(source_lines[:start])
            new_source += '\n' + indent(dedent(source_code_str.strip()), '\t') + '\n'
            new_source += '\n'.join(source_lines[end:])
        except ValueError:
            new_source = self._source + '\n' + indent(dedent(source_code_str.strip()), '\t') + '\n'
        self._source = new_source.rstrip('\n').replace('\t', '    ') 
开发者ID:robbert-harms,项目名称:MDT,代码行数:21,代码来源:utils.py

示例13: get_ansible_vars

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def get_ansible_vars(self, triggering_instance_id=None):
        """
        Render the configuration script to be executed on the load balancer.

        The triggering_instance_id indicates the id of the instance reference that initiated the
        reconfiguration of the load balancer.
        """
        backend_map, backend_conf = self.get_configuration(triggering_instance_id)
        fragment_name = settings.LOAD_BALANCER_FRAGMENT_NAME_PREFIX + self.fragment_name_postfix
        return (
            "FRAGMENT_NAME: {fragment_name}\n"
            "BACKEND_CONFIG_FRAGMENT: |\n"
            "{backend_conf}\n"
            "BACKEND_MAP_FRAGMENT: |\n"
            "{backend_map}\n"
        ).format(
            fragment_name=fragment_name,
            backend_conf=textwrap.indent(backend_conf, "  "),
            backend_map=textwrap.indent(backend_map, "  "),
        ) 
开发者ID:open-craft,项目名称:opencraft,代码行数:22,代码来源:load_balancer.py

示例14: test_source_with_decorator

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def test_source_with_decorator() -> None:
    """Test behavior with Source / Code().source with regard to decorators."""
    from _pytest.compat import get_real_func

    @pytest.mark.foo
    def deco_mark():
        assert False

    src = inspect.getsource(deco_mark)
    assert textwrap.indent(str(Source(deco_mark)), "    ") + "\n" == src
    assert src.startswith("    @pytest.mark.foo")

    @pytest.fixture
    def deco_fixture():
        assert False

    src = inspect.getsource(deco_fixture)
    assert src == "    @pytest.fixture\n    def deco_fixture():\n        assert False\n"
    # currenly Source does not unwrap decorators, testing the
    # existing behavior here for explicitness, but perhaps we should revisit/change this
    # in the future
    assert str(Source(deco_fixture)).startswith("@functools.wraps(function)")
    assert (
        textwrap.indent(str(Source(get_real_func(deco_fixture))), "    ") + "\n" == src
    ) 
开发者ID:pytest-dev,项目名称:pytest,代码行数:27,代码来源:test_source.py

示例15: run

# 需要导入模块: import textwrap [as 别名]
# 或者: from textwrap import indent [as 别名]
def run(self):
        total_bytes = 0
        count = 0
        bad_items = 0
        for item in get_items_for_snapshot_version(self.client, self.snapshot_version):
            total_bytes += item['bytes']
            count += 1
            logger.debug('Checking %s', item['name'])
            if item.get('missing'):
                bad_items += 1
                logger.warning('Missing shard file: %s', item['name'])
            if count % 100 == 0:
                logger.info('Checked %s items (%s)', count, sizeof_fmt(total_bytes))

        state = f'INVALID ({bad_items} files missing)' if bad_items else 'VALID'
        print(
            f'Snapshot version {self.snapshot_version}:\n'
            f'    File count: {count}\n'
            f'    Total size: {sizeof_fmt(total_bytes)}\n'
            f'    State:      {state}\n'
        )

        if self.metadata:
            metadata = self.client.get_json(f'snapshot-{self.snapshot_version}')
            print(json.dumps(metadata, indent=4)) 
开发者ID:dimagi,项目名称:commcare-cloud,代码行数:27,代码来源:es_snapshot.py


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