我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用textwrap.indent()。
def indent(text, prefix, predicate=None): """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())
def info (self, verbose=False): ''' Get a string describing various properties of the app. ''' offset = self.address fields = self.tbfh.fields out = '' out += 'Name: {}\n'.format(self.name) out += 'Enabled: {}\n'.format(self.tbfh.is_enabled()) out += 'Sticky: {}\n'.format(self.tbfh.is_sticky()) out += 'Total Size in Flash: {} bytes\n'.format(self.get_size()) if verbose: out += textwrap.indent(str(self.tbfh), ' ') return out
def _print_apps (self, apps, verbose, quiet): ''' Print information about a list of apps ''' if not quiet: # Print info about each app for i,app in enumerate(apps): print('[App {}]'.format(i)) # Check if this app is OK with the MPU region requirements. if not self._app_is_aligned_correctly(app.address, app.get_size()): print(' [WARNING] App is misaligned for the MPU') print(textwrap.indent(app.info(verbose), ' ')) print('') if len(apps) == 0: print('No found apps.') else: # In quiet mode just show the names. app_names = [] for app in apps: app_names.append(app.name) print(' '.join(app_names))
def __str__(self): c = '' c += 'public class ' + self._name + ' {\n\n' if self._is_start: c += ' public void eval() {\n' c += indent(self._eval, ' '*2) + '\n' c += ' }\n\n' c += ' private ' + self._name + '() {}\n\n' c += ' Context$ context() {\n' c += ' return null;\n' c += ' }\n\n' if not self._name.startswith('_'): c += ' public static final class StartingMethods {\n\n' c += ' private StartingMethods() {}\n\n' for m in sorted(self._starts): c += indent(str(m), ' '*2) + '\n\n' c += ' }\n\n' for stc in sorted(self._stcs): c += indent(str(stc), ' ') + '\n\n' c += '}' return c
def __str__(self): c = '' c += 'public static final class State' + self._idx + '<T>' c += ' extends {}'.format(self._name) if self._extends else '' c += ' {\n\n' c += ' final Context$ context;\n\n' c += ' State' + self._idx + '(Context$ context) {\n' c += ' this.context = context;\n' c += ' }\n\n' if self._extends: c += ' Context$ context() {\n' c += ' return context;\n' c += ' }\n\n' for m in sorted(self._methods): c += indent(str(m), ' ') + '\n\n' c += '}' return c
def __str__(self): r = self._ret n = self._name a = self._arg c = '' c += 'public ' + r + ' ' + n + '(' + a + ') {\n' if self._madd: c += indent(self._madd, ' ') + '\n' if self._cpush: c += ' ' + self._cpush + '\n' c += indent(self._new, ' ') + '\n' c += '}' if r == 'T': c = '@SuppressWarnings("unchecked")\n' + c return c
def print_pretty(msg, *, status=PrintStatus.NONE, file=None): if file is None: file = sys.stderr if status == PrintStatus.NONE: indicator = '\x1b[96m\u2219' if file.isatty() else '\u2219' elif status == PrintStatus.WAITING: assert '\n' not in msg, 'Waiting message must be a single line.' indicator = '\x1b[93m\u22EF' if file.isatty() else '\u22EF' elif status == PrintStatus.DONE: indicator = '\x1b[92m\u2714' if file.isatty() else '\u2714' elif status == PrintStatus.FAILED: indicator = '\x1b[91m\u2718' if file.isatty() else '\u2718' else: raise ValueError if file.isatty(): print('\x1b[2K', end='', file=file) text = textwrap.indent(msg, ' ') text = indicator + text[1:] if file.isatty(): text += '\x1b[0m' print('{0}\r'.format(text), end='', file=file) file.flush() if status != PrintStatus.WAITING: print('', file=file)
def parse(self, s): if not s: return else: for match in self.re_token.finditer(s): imatch = self.re_indent.fullmatch(match.group(1)) if imatch: text = imatch.group(1) self.indent = imatch.group(2) else: text = match.group(1) self.indent = "" if match.group(2) is None: if match.end() != len(s): raise Exception( "Not terminated token: %r" % s[match.end():]) yield (text, None, None, None) break else: fmatch = self.re_field.fullmatch(match.group(2)) if not fmatch: raise Exception( "Cannot parse token: %r" % match.group(2)) yield (text, fmatch.group(1), fmatch.group(3), fmatch.group(2))
def format_error(self, script, res) -> str: template = ''' {cmd} Script: {script} Output: {stderr} ''' def indent(text, prefix='> '): return textwrap.indent(text.strip(), prefix, lambda line: True) template = textwrap.dedent(template).rstrip() return template.format( cmd=indent(' '.join(res.args)), script=indent(script), stderr=indent(res.stderr.decode('utf8')), )
def exit_with_error(e, header='An error has been encountered:', file=None, suppress_footer=False): import sys import traceback import textwrap import click if file is None: file = sys.stderr footer = 'See above for debug info.' else: footer = 'Debug info has been saved to %s' % file.name error = textwrap.indent(str(e), ' ') segments = [header, error] if not suppress_footer: segments.append(footer) traceback.print_exception(type(e), e, e.__traceback__, file=file) file.write('\n') click.secho('\n\n'.join(segments), fg='red', bold=True, err=True) click.get_current_context().exit(1)
def _build_section(self, header, iterable): section = [] if iterable: section.append(header) section.append('-'*len(header)) for key, value in iterable.items(): variable_line = ( "{item} : {type}".format(item=key, type=value.qiime_type)) if value.has_default(): variable_line += ", optional" section.append(variable_line) if value.has_description(): section.append(textwrap.indent(textwrap.fill( str(value.description), width=71), ' ')) return '\n'.join(section).strip()
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', ' ')
def __init__(self, *, wrap_code=False, strip_ticks=True, indent_width=4, implicit_return=False): """ A converter that extracts code out of code blocks and inline code formatting. Parameters ---------- wrap_code Specifies whether to wrap the resulting code in a function. strip_ticks Specifies whether to strip the code of formatting-related backticks. indent_width Specifies the indent width, if wrapping. implicit_return Automatically adds a return statement, when wrapping code. """ self.wrap_code = wrap_code self.strip_ticks = strip_ticks self.indent_width = indent_width self.implicit_return = implicit_return
def _format(self, content: str) -> str: """Format plain text for the text output. Args: content: The text to be formatted. Returns: The formatted text as a string. """ if self.formatter.manual_markup: output_text, positions = self.parse_manual_markup(content) else: output_text, positions = content, MarkupPositions([], []) wrapper = textwrap.TextWrapper(width=self._width) output_text = wrapper.fill(output_text) output_text = self._apply_markup(output_text, positions) return textwrap.indent(output_text, " "*self._current_indent)
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!
def test_indent_default(self): # Test default indenting of lines that are not whitespace only prefix = ' ' expected = ( # Basic test case " Hi.\n This is a test.\n Testing.", # Include a blank line " Hi.\n This is a test.\n\n Testing.", # Include leading and trailing blank lines "\n Hi.\n This is a test.\n Testing.\n", # Use Windows line endings " Hi.\r\n This is a test.\r\n Testing.\r\n", # Pathological case "\n Hi.\r\n This is a test.\n\r\n Testing.\r\n\n", ) for text, expect in zip(self.CASES, expected): self.assertEqual(indent(text, prefix), expect)
def test_indent_explicit_default(self): # Test default indenting of lines that are not whitespace only prefix = ' ' expected = ( # Basic test case " Hi.\n This is a test.\n Testing.", # Include a blank line " Hi.\n This is a test.\n\n Testing.", # Include leading and trailing blank lines "\n Hi.\n This is a test.\n Testing.\n", # Use Windows line endings " Hi.\r\n This is a test.\r\n Testing.\r\n", # Pathological case "\n Hi.\r\n This is a test.\n\r\n Testing.\r\n\n", ) for text, expect in zip(self.CASES, expected): self.assertEqual(indent(text, prefix, None), expect)
def test_indent_all_lines(self): # Add 'prefix' to all lines, including whitespace-only ones. prefix = ' ' expected = ( # Basic test case " Hi.\n This is a test.\n Testing.", # Include a blank line " Hi.\n This is a test.\n \n Testing.", # Include leading and trailing blank lines " \n Hi.\n This is a test.\n Testing.\n", # Use Windows line endings " Hi.\r\n This is a test.\r\n Testing.\r\n", # Pathological case " \n Hi.\r\n This is a test.\n \r\n Testing.\r\n \n", ) predicate = lambda line: True for text, expect in zip(self.CASES, expected): self.assertEqual(indent(text, prefix, predicate), expect)
def test_indent_empty_lines(self): # Add 'prefix' solely to whitespace-only lines. prefix = ' ' expected = ( # Basic test case "Hi.\nThis is a test.\nTesting.", # Include a blank line "Hi.\nThis is a test.\n \nTesting.", # Include leading and trailing blank lines " \nHi.\nThis is a test.\nTesting.\n", # Use Windows line endings "Hi.\r\nThis is a test.\r\nTesting.\r\n", # Pathological case " \nHi.\r\nThis is a test.\n \r\nTesting.\r\n \n", ) predicate = lambda line: not line.strip() for text, expect in zip(self.CASES, expected): self.assertEqual(indent(text, prefix, predicate), expect)
def add_to_message(data, indent_level=0) -> list: """ Adds data to the message object """ m = [] if isinstance(data, str): m.append(indent( dedent(data.strip('\n')).strip(), indent_level * ' ' )) return m for line in data: if isinstance(line, str): m += add_to_message(line, indent_level) else: m += add_to_message(line, indent_level + 1) return m
def format_assignment_gist(recording, debug=False): """Given a single recording, format it into a markdown file. Each recording will only have one student. Returns a {content: str, student: str, type: str} dict. """ try: files = format_files_list(recording.get('files', {})) warnings = format_warnings(recording.get('warnings', {}).items()) header = format_header(recording, warnings) output = (header + files) + '\n\n' except Exception as err: if debug: raise err output = indent(traceback.format_exc(), ' ' * 4) + '\n\n' return { 'content': output, 'student': recording['student'], 'type': 'md', }
def format_file(filename, file_info): contents = format_file_contents(file_info.get('contents', ''), file_info) + '\n' compilation = format_file_compilation(file_info.get('compilation', [])) + '\n' test_results = format_file_results(file_info.get('result', [])) + '\n' if file_info.get('last modified', None): last_modified = ' ({})'.format(file_info['last modified']) else: last_modified = '' file_header = '## {}{}\n'.format(filename, last_modified) if file_info['missing']: note = 'File not found. `ls .` says that these files exist:\n' directory_listing = indent('\n'.join(file_info.get('other files', [])), ' ' * 4) if file_info['optional']: file_header = file_header.strip() file_header += ' (**optional submission**)\n' return '\n'.join([file_header, note, directory_listing + '\n\n']) return '\n'.join([file_header, contents, compilation, test_results])
def format_assignment_markdown(recording, debug=False): """Given a single recording, format it into a markdown file. Each recording will only have one student. Returns a {content: str, student: str, type: str, assignment: str} dict. """ try: files = format_files_list(recording.get('files', {})) warnings = format_warnings(recording.get('warnings', {}).items()) header = format_header(recording, warnings) output = (header + files) + '\n\n' except Exception as err: if debug: raise err output = indent(traceback.format_exc(), ' ' * 4) + '\n\n' return { 'assignment': recording['spec'], 'content': output, 'student': recording['student'], 'type': 'md', }
def format_description(content, width=70, indent=8, indent_first=False): """Format documentation description""" # TODO: document, test, and use lines = content.splitlines() def format_line(line): if line.startswith('-'): return textwrap.indent(textwrap.fill(line, width - indent - 2), (indent + 2) * ' ')[2:] else: return textwrap.indent(textwrap.fill(line, width - indent), indent * ' ') result = '\n'.join(format_line(line) for line in lines if line) if not indent_first: result = result.lstrip() return result
def add_param_docs(param_map): """ Append documentation from FLAG_MAP to a function's docstring. :param param_map: A mapping of argument names (strings) to FlagInfo objects. :return: A decorator that appends flag information to a function's docstring. """ def decorator(func): func.__doc__ = textwrap.dedent(func.__doc__) + '\n'.join( ':param {}:\n{}'.format(name, textwrap.indent(arg.doc, ' ')) for name, arg in param_map.items()) return func return decorator # Mypy generates messages in the format: # blabla.py: note: In function "f": # blabla.py:2: error: Unsupported operand types for ... # The "note" messages are only adding info coala should already know, # so discard those. We're only capturing the errors.
def write(self, msg, depth=0): if depth: prefix = self.INDENT * depth msg = indent(msg, prefix) return super(CodeWriter, self).write(msg)
def buildFacade(schema): cls = type(schema.name, (Type,), dict(name=schema.name, version=schema.version, schema=schema)) source = """ class {name}Facade(Type): name = '{name}' version = {version} schema = {schema} """.format(name=schema.name, version=schema.version, schema=textwrap.indent(pprint.pformat(schema), " ")) return cls, source
def __str__ (self): out = '' metadata = self.parse_metadata() out += 'TAB: {}\n'.format(metadata['name']) for k,v in sorted(metadata.items()): if k == 'name': continue out += ' {}: {}\n'.format(k,v) out += ' supported architectures: {}\n'.format(', '.join(self.get_supported_architectures())) out += ' TBF Header\n' out += textwrap.indent(str(self.get_tbf_header()), ' ') return out
def __str__(self): return "{}: {}\n".format( self.tag and self.tag.name, self.tag and self.tag.text_content ) + indent("".join(str(child) for child in self.children), " " * 4)
def str(self, highlight=False) -> str: s = '' if self.name: s = sformat(self.name, sformat.blue, apply=highlight) + ': ' s += pformat(self.value, indent=4, highlight=highlight) suffix = ( ' ({0.value.__class__.__name__}) {1}' .format(self, ' '.join('{}={}'.format(k, v) for k, v in self.extra)) .rstrip(' ') # trailing space if extra is empty ) s += sformat(suffix, sformat.dim, apply=highlight) return s
def _wrap_parse(code, filename): """ async wrapper is required to avoid await calls raising a SyntaxError """ code = 'async def wrapper():\n' + indent(code, ' ') return ast.parse(code, filename=filename).body[0].body[0].value
def indent(text, prefix, predicate=None): 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())