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())
python类indent()的实例源码
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 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 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 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 __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 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 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 __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 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 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!