當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。