def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
python类wrap()的实例源码
def prefixed_wrap(prefix, text, width=None, indent=0):
"""
Wrap text with a prefix and optionally indenting the second and
later lines. If the width is None, the terminal size will be
used. (See terminal_size() for details.)
"""
if width is None:
height, width = terminal_size()
wrapped = textwrap.wrap(text, width - len(prefix))
leader = " " * (len(prefix) + indent)
lines = [wrapped.pop(0)]
lines.extend(["%s%s" % (leader, line)
for line in wrapped])
return "%s%s" % (prefix, "\n".join(lines))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def say(bot, msg, target, requestor, characters : int = 2000, maxMessage = 5):
"""A helper function to get the bot to cut his text into chunks."""
if not bot or not msg or not target:
return False
textList = textwrap.wrap(msg, characters, break_long_words=True, replace_whitespace=False)
if not len(textList):
return False
if len(textList) > maxMessage and not target == requestor:
# PM the contents to the requestor
await bot.send_message(target, "Since this message is *{} pages* - I'm just going to DM it to you.".format(len(textList)))
target = requestor
for message in textList:
await bot.send_message(target, message)
return True
def pprint():
print('')
print('-'*LINE_WIDTH)
print('')
for chall_id in Challenge.index():
chall = Challenge(chall_id)
print('ID: %s (%d points) [%s]' % (
chall.id,
chall['points'],
', '.join(chall['tags'])))
print('')
print(chall['title'])
print('')
print('\n'.join(textwrap.wrap(chall['description'],
LINE_WIDTH)))
print('')
print('-'*LINE_WIDTH)
print('')
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def send(bot, text, private=False, notice=False):
"""Send irc message."""
text = str(text)
tr = bot._trigger
jarvis.db.Message.create(
user=bot.config.core.nick,
channel=tr.sender,
time=arrow.utcnow().timestamp,
text=text)
mode = 'NOTICE' if notice else 'PRIVMSG'
recipient = tr.nick if private or notice else tr.sender
try:
bot.sending.acquire()
text = textwrap.wrap(text, width=420)[0]
bot.write((mode, recipient), text)
finally:
bot.sending.release()
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def send_chat(self, value, global_message=False):
if self.deaf:
return
if not global_message:
chat_message.chat_type = CHAT_SYSTEM
prefix = ''
else:
chat_message.chat_type = CHAT_TEAM
# 34 is guaranteed to be out of range!
chat_message.player_id = 35
prefix = self.protocol.server_prefix + ' '
lines = textwrap.wrap(value, MAX_CHAT_SIZE - len(prefix) - 1)
for line in lines:
chat_message.value = '%s%s' % (prefix, line)
self.send_contained(chat_message)
def add_summary_section(self):
""" Coverage section.
"""
#image = self.create_embedded_png(self.chromosome.plot_coverage,
# input_arg="filename")
import textwrap
command = "\n".join(textwrap.wrap(self.jinja['command'], 80))
command = self.jinja['command']
html = "<p>Data type: {} </p>".format(self.jinja["mode"])
html += '<div style="textwidth:80%">Command: <pre>{}</pre></div>'.format(command)
self.sections.append({
"name": "Data and command used",
"anchor": "cutadapt",
"content": html
})
def draw_spotteditems_panel(panel):
""" draws items below the player a panel """
# Draw what the player can see at his feet
spotted = [obj.name for obj in get_items() if (obj.x, obj.y) == gv.player.pos()]
if len(spotted): # if more than one object is present, output the names as a message
x = 2
y = settings.STAT_PANEL_HEIGHT // 2
panel.draw_str(x, settings.STAT_PANEL_HEIGHT // 2, 'At your feet:', bg=None, fg=colors.white)
y += 2
for obj in spotted: # Go through the object names and wrap them according to the panel's width
line_wrapped = wrap(obj, panel.width - 3)
if y + len(
line_wrapped) < panel.height - 2: # As long as we don't exceed the panel's height, draw the items
for text in line_wrapped:
panel.draw_str(x, y, text, bg=None, fg=colors.white)
y += 1
else: # otherwise draw a line to indicate there's more than can be displayed
panel.draw_str((panel.width - 6) // 2, panel.height - 1, '< MORE >')
break
def __init__(self, text, msg_type=MessageType.INFO_GENERIC, log_level=LogLevel.NONCOMBAT, log=None):
self.text = text
self.msg_type = msg_type
self.log_level = log_level
self.log = log
if self.log is None:
self.log = gv.game_log
self.color = colors.white
# set messages color
self.set_color()
# Format the passed text according to the intended log's width
self.lines = textwrap.wrap(self.text, self.log.width - 2)
# Add the Message to the intended log
self.log.messages.append(self)
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def _help(self, *args, message):
if len(args) == 0:
docs = list(self.prefix + key + (f" ({cmd.hint})" if cmd.hint else "")
for key, cmd in self._commands.items() if key not in ("bots", "help"))
lines = textwrap.wrap("; ".join(docs), width=400)
for line in lines:
if isinstance(message.recipient, Channel):
await message.sender.message(line, notice=True)
else:
await message.sender.message(line)
elif len(args) == 1:
cmd = self._commands.get(args[0])
if not cmd:
return
if not cmd.doc:
await message.sender.message(
"No help available for that command",
notice=True)
else:
for line in cmd.doc.split("\n"):
await message.sender.message(line, notice=True)
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def print_exception(exc):
"""
Prints the exception string to StdErr. XML tags are stripped.
"""
error_string = ""
if isinstance(exc, Exception):
if not isinstance(exc, NoTraceException):
_, _, error_string, _ = get_error_repr(sys.exc_info())
error_string = "TRACE:\n{}".format(error_string)
error_string += "ERROR {}: {}\n".format(type(exc).__name__, exc)
else:
error_string = exc
for par in [x.strip(" ") for x in error_string.split("</p>") if x.strip(" ")]:
par = par.replace("\n", " ").strip(" ")
par = par.replace(" ", " ")
print("\n".join(
textwrap.wrap(re.sub('<[^>]*>', '', par), width=70, replace_whitespace=False)),
file=sys.stderr)
print(file=sys.stderr)
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def deprecated(self, msg, version=None, removed=False):
''' used to print out a deprecation message.'''
if not removed and not C.DEPRECATION_WARNINGS:
return
if not removed:
if version:
new_msg = "[DEPRECATION WARNING]: %s.\nThis feature will be removed in version %s." % (msg, version)
else:
new_msg = "[DEPRECATION WARNING]: %s.\nThis feature will be removed in a future release." % (msg)
new_msg = new_msg + " Deprecation warnings can be disabled by setting deprecation_warnings=False in ansible.cfg.\n\n"
else:
raise AnsibleError("[DEPRECATED]: %s.\nPlease update your playbooks." % msg)
wrapped = textwrap.wrap(new_msg, self.columns, replace_whitespace=False, drop_whitespace=False)
new_msg = "\n".join(wrapped) + "\n"
if new_msg not in self._deprecations:
self.display(new_msg.strip(), color=C.COLOR_DEPRECATE, stderr=True)
self._deprecations[new_msg] = 1
def _wrap_section(source, width):
# type: (str, int) -> str
"""Wrap the given section string to the current terminal size.
Intelligently wraps the section string to the given width. When wrapping
section lines, it auto-adjusts the spacing between terms and definitions.
It also adjusts commands the fit the correct length for the arguments.
Args:
source: The section string to wrap.
Returns:
The wrapped section string.
"""
if _get_section('usage', source):
return _wrap_usage_section(source, width)
if _is_definition_section(source):
return _wrap_definition_section(source, width)
lines = inspect.cleandoc(source).splitlines()
paragraphs = (textwrap.wrap(line, width, replace_whitespace=False)
for line in lines)
return '\n'.join(line for paragraph in paragraphs for line in paragraph)
def _wrap_definition_section(source, width):
# type: (str, int) -> str
"""Wrap the given definition section string to the current terminal size.
Note:
Auto-adjusts the spacing between terms and definitions.
Args:
source: The section string to wrap.
Returns:
The wrapped section string.
"""
index = source.index('\n') + 1
definitions, max_len = _get_definitions(source[index:])
sep = '\n' + ' ' * (max_len + 4)
lines = [source[:index].strip()]
for arg, desc in six.iteritems(definitions):
wrapped_desc = sep.join(textwrap.wrap(desc, width - max_len - 4))
lines.append(' {arg:{size}} {desc}'.format(
arg=arg,
size=str(max_len),
desc=wrapped_desc
))
return '\n'.join(lines)
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def do_wordwrap(environment, s, width=79, break_long_words=True,
wrapstring=None):
"""
Return a copy of the string passed to the filter wrapped after
``79`` characters. You can override this default using the first
parameter. If you set the second parameter to `false` Jinja will not
split words apart if they are longer than `width`. By default, the newlines
will be the default newlines for the environment, but this can be changed
using the wrapstring keyword argument.
.. versionadded:: 2.7
Added support for the `wrapstring` parameter.
"""
if not wrapstring:
wrapstring = environment.newline_sequence
import textwrap
return wrapstring.join(textwrap.wrap(s, width=width, expand_tabs=False,
replace_whitespace=False,
break_long_words=break_long_words))
def wrap_paragraphs(text, ncols=80):
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
Returns
-------
list of complete paragraphs, wrapped to fill `ncols` columns.
"""
paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
text = dedent(text).strip()
paragraphs = paragraph_re.split(text)[::2] # every other entry is space
out_ps = []
indent_re = re.compile(r'\n\s+', re.MULTILINE)
for p in paragraphs:
# presume indentation that survives dedent is meaningful formatting,
# so don't fill unless text is flush.
if indent_re.search(p) is None:
# wrap paragraph
p = textwrap.fill(p, ncols)
out_ps.append(p)
return out_ps
def wrap_paragraphs(text, ncols=80):
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
Returns
-------
list of complete paragraphs, wrapped to fill `ncols` columns.
"""
paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
text = dedent(text).strip()
paragraphs = paragraph_re.split(text)[::2] # every other entry is space
out_ps = []
indent_re = re.compile(r'\n\s+', re.MULTILINE)
for p in paragraphs:
# presume indentation that survives dedent is meaningful formatting,
# so don't fill unless text is flush.
if indent_re.search(p) is None:
# wrap paragraph
p = textwrap.fill(p, ncols)
out_ps.append(p)
return out_ps
def displaySpoitfyTitle():
# Write some text.
text = " -=SPOTIFY=- " + spconnect('metadata','track_name') +" - " + spconnect('metadata','artist_name')
#print text
lines = textwrap.wrap(text, width=24)
current_h, pad = 0, 0
font = ImageFont.load_default()
font2 = ImageFont.truetype('fonts/C&C Red Alert [INET].ttf', 12)
with canvas(disp) as draw:
for line in lines:
w, h = draw.textsize(line, font=font2)
draw.text(((128 - w) / 2, current_h), line, font=font2, fill=255)
current_h += h + pad