Python textwrap.indent() Examples

The following are 30 code examples of textwrap.indent(). 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 textwrap , or try the search function .
Example #1
Source File: debug.py    From python-devtools with MIT License 7 votes vote down vote up
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 
Example #2
Source File: core.py    From ibis with Apache License 2.0 6 votes vote down vote up
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) 
Example #3
Source File: presto-entrypoint.py    From presto-chart with MIT License 6 votes vote down vote up
def launch(arguments: dict):
    """Starts the presto service running within the container."""
    conf_dir = CONFIGS_DIRECTORY
    print('\n[LAUNCH]: Starting Presto')
    cmd = [
        'launcher', 'run',
        '--node-config={}/node.properties'.format(conf_dir),
        '--jvm-config={}/jvm.config'.format(conf_dir),
        '--config={}/config.properties'.format(conf_dir),
        '--log-levels-file={}/log.properties'.format(conf_dir)
    ]

    print(textwrap.indent('\n'.join(cmd), '  '), '\n\n')
    if not arguments['dry_run']:
        subprocess.run(cmd)
    else:
        print('[DRY-RUN]: Skipped launch call\n\n') 
Example #4
Source File: es_snapshot.py    From commcare-cloud with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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)) 
Example #5
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 6 votes vote down vote up
def test_subsequent_indent(self):
        # Test subsequent_indent parameter

        expect = '''\
  * This paragraph will be filled, first
    without any indentation, and then
    with some (including a hanging
    indent).'''

        result = fill(self.text, 40,
                      initial_indent="  * ", subsequent_indent="    ")
        self.check(result, expect)


# Despite the similar names, DedentTestCase is *not* the inverse
# of IndentTestCase! 
Example #6
Source File: patches.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #7
Source File: test_source.py    From pytest with MIT License 6 votes vote down vote up
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
    ) 
Example #8
Source File: svn.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
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 
Example #9
Source File: load_balancer.py    From opencraft with GNU Affero General Public License v3.0 6 votes vote down vote up
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, "  "),
        ) 
Example #10
Source File: patches.py    From GraphicDesignPatternByPython with MIT License 6 votes vote down vote up
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) 
Example #11
Source File: utils.py    From exhale with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #12
Source File: utils.py    From MDT with GNU Lesser General Public License v3.0 6 votes vote down vote up
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', '    ') 
Example #13
Source File: eval.py    From modmail with GNU Affero General Public License v3.0 6 votes vote down vote up
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```" 
Example #14
Source File: scrapers.py    From sphinx-gallery with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #15
Source File: patches.py    From Mastering-Elasticsearch-7.0 with MIT License 6 votes vote down vote up
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) 
Example #16
Source File: scopetree.py    From edgedb with Apache License 2.0 6 votes vote down vote up
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 '' 
Example #17
Source File: tables.py    From edgedb with Apache License 2.0 6 votes vote down vote up
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 
Example #18
Source File: utils.py    From exhale with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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()) 
Example #19
Source File: split_node.py    From scikit-multiflow with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
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) 
Example #20
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_initial_indent(self):
        # Test initial_indent parameter

        expect = ["     This paragraph will be filled,",
                  "first without any indentation, and then",
                  "with some (including a hanging indent)."]
        result = wrap(self.text, 40, initial_indent="     ")
        self.check(result, expect)

        expect = "\n".join(expect)
        result = fill(self.text, 40, initial_indent="     ")
        self.check(result, expect) 
Example #21
Source File: lifecycle.py    From vivarium with GNU General Public License v3.0 5 votes vote down vote up
def __str__(self) -> str:
        out = self.name
        if self._loop:
            out += '*'
        out += '\n' + textwrap.indent('\n'.join([str(state) for state in self.states]), '\t')
        return out 
Example #22
Source File: tzxls.py    From tzxtools with GNU General Public License v3.0 5 votes vote down vote up
def main():
    parser = argparse.ArgumentParser(description='List the contents of a TZX file')
    parser.add_argument('file',
                nargs='*',
                help='TZX files, stdin if omitted')
    parser.add_argument('-s', '--short',
                dest='short',
                action='store_true',
                help='list only the ZX Spectrum header names')
    parser.add_argument('-v', '--verbose',
                dest='verbose',
                action='store_true',
                help='show content of information blocks')
    args = parser.parse_args()

    for f in args.file if len(args.file) > 0 else ['/dev/stdin']:
        if len(args.file) > 1:
            print('\n%s:' % (f))

        tzx = TzxFile()
        tzx.read(f)

        cnt = 0
        for b in tzx.blocks:
            if args.short:
                if hasattr(b, 'tap') and isinstance(b.tap, TapHeader):
                    print('%s: %s' % (b.tap.type(), b.tap.name()))
            else:
                print('%3d  %-27s %s' % (cnt, b.type, str(b)))
            if args.verbose:
                info = b.info()
                if info is not None:
                    print(textwrap.indent(info.strip(), '\t'))
            cnt += 1 
Example #23
Source File: printer.py    From sota-extractor with Apache License 2.0 5 votes vote down vote up
def wrap_lines(value, indent=4) -> List[str]:
    prefix = " " * indent
    return [
        textwrap.indent(line, prefix=prefix) for line in textwrap.wrap(value)
    ] 
Example #24
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_fill(self):
        # Test the fill() method

        expect = '''\
This paragraph will be filled, first
without any indentation, and then with
some (including a hanging indent).'''

        result = fill(self.text, 40)
        self.check(result, expect) 
Example #25
Source File: core.py    From ibis with Apache License 2.0 5 votes vote down vote up
def visit_For(self, node):
        lines = [
            'for (let {} of {}) {{'.format(
                self.visit(node.target), self.visit(node.iter)
            )
        ]
        with self.local_scope():
            lines.append(indent(map(self.visit, node.body)))
        lines.append('}')
        return '\n'.join(lines) 
Example #26
Source File: structure.py    From smbprotocol with MIT License 5 votes vote down vote up
def _indent_lines(string, prefix):
    # Would use textwrap.indent for this but it is not available for Python 2
    def predicate(line):
        return line.strip()

    lines = []
    for line in string.splitlines(True):
        lines.append(prefix + line if predicate(line) else line)
    return ''.join(lines) 
Example #27
Source File: core.py    From ibis with Apache License 2.0 5 votes vote down vote up
def visit_FunctionDef(self, node):
        self.current_function = node

        is_property_getter = any(
            getattr(dec, 'id', None) == 'property'
            for dec in node.decorator_list
        )

        if self.current_class is None:  # not a method
            if is_property_getter:
                raise TypeError(
                    'Functions cannot be properties, only methods can'
                )
            prefix = 'function'
        else:
            if is_property_getter and self.is_generator:
                raise TypeError('generator methods cannot be properties')
            prefix = 'get ' * is_property_getter

        with self.local_scope():
            body = indent(map(self.visit, node.body))

            if self.is_generator:
                prefix += '* '
            else:
                prefix += ' ' * (self.current_class is None)

            lines = [
                prefix
                + self.translate_special_method(node.name)
                + '({}) {{'.format(self.visit(node.args)),
                body,
                '}',
            ]

            self.current_function = None
            self.is_generator = False
        return '\n'.join(lines) 
Example #28
Source File: core.py    From ibis with Apache License 2.0 5 votes vote down vote up
def visit_If(self, node):
        lines = ['if ({}) {{'.format(self.visit(node.test))]

        with self.local_scope():
            lines.append(indent(map(self.visit, node.body)))
            lines.append('}')

        if node.orelse:
            lines[-1] += ' else {'
            with self.local_scope():
                lines.append(indent(map(self.visit, node.orelse)))
                lines.append('}')
        return '\n'.join(lines) 
Example #29
Source File: core.py    From ibis with Apache License 2.0 5 votes vote down vote up
def visit_While(self, node):
        lines = ['while ({}) {{'.format(self.visit(node.test))]
        with self.local_scope():
            lines.append(indent(map(self.visit, node.body)))
        lines.append('}')
        return '\n'.join(lines) 
Example #30
Source File: decorators.py    From qiskit-terra with Apache License 2.0 5 votes vote down vote up
def _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Callable:
    """Update annotations of discretized continuous pulse function.

    Args:
        discretized_pulse: Discretized decorated continuous pulse.
        sampler_inst: Applied sampler.
    """
    wrapped_docstring = pydoc.render_doc(discretized_pulse, '%s')
    header, body = wrapped_docstring.split('\n', 1)
    body = textwrap.indent(body, '                    ')
    wrapped_docstring = header+body
    updated_ds = """
                Discretized continuous pulse function: `{continuous_name}` using
                sampler: `{sampler_name}`.

                 The first argument (time) of the continuous pulse function has been replaced with
                 a discretized `duration` of type (int).

                 Args:
                     duration (int)
                     *args: Remaining arguments of continuous pulse function.
                            See continuous pulse function documentation below.
                     **kwargs: Remaining kwargs of continuous pulse function.
                               See continuous pulse function documentation below.

                 Sampled continuous function:

                    {continuous_doc}
                """.format(continuous_name=discretized_pulse.__name__,
                           sampler_name=sampler_inst.__name__,
                           continuous_doc=wrapped_docstring)

    discretized_pulse.__doc__ = updated_ds
    return discretized_pulse