def add_long_text(self, text):
wrapper = textwrap.TextWrapper()
wrapper.width = self.width - 4
i = 0
for line in wrapper.wrap(text):
if len(line) == 0:
self.blank_line()
else:
# get filler spaces
spaces = ''
i = self.width - len(line) - 4
while i > 0:
spaces += ' '
i -= 1
# add the line
bordered_line = colored(u'\u2502 ', self.border_color)
bordered_line += colored(line + spaces, self.text_color)
bordered_line += colored(' ' + u'\u2502', self.border_color)
self.text.append(bordered_line)
# adds a line which may contain color tags
python类TextWrapper()的实例源码
def get_commit_messages_since(self, version):
"""Return a formatted list of commit messages since the given tagged version."""
tag = '{}.{}.{}'.format(*version)
output = util.communicate([
'git', 'log',
'--pretty=format:{{{{%w(0,0,0)%s %b}}}}',
'--reverse', tag + '..'
])
# Split the messages, they are bounded by {{{{ }}}}
messages = []
for match in self.COMMIT_MSG_RE.finditer(output):
messages.append(match.group(1).strip())
# Wrap the messages
wrapper = TextWrapper(initial_indent='- ', subsequent_indent=' ')
messages = list(map(lambda msg: '\n'.join(wrapper.wrap(msg)), messages))
return '\n\n'.join(messages) + '\n'
def printInd(s, level=1, length=70, prefix=''):
from textwrap import TextWrapper
indents={1: 0, 2: 4, 3: 8, 4: 12, 5: 16}
ind=indents[level]
indstr=' '*int(ind)
wrapper=TextWrapper()
wrapper.width=length
wrapper.initial_indent=indstr
wrapper.subsequent_indent=indstr
string=wrapper.fill('%s %s' %(prefix,s))
try:
print('\n'+string)
except:
print('\n'+string.encode('ascii','replace'))
return
#-------------------Read in text file and store data-------------------
def setup_logger(self):
"""
Initialize the logger.
"""
class TextwrapFormatter(logging.Formatter):
def __init__(self, fmt):
super(TextwrapFormatter, self).__init__(fmt=fmt)
self.wrap = textwrap.TextWrapper(width=79, subsequent_indent=" ").fill
def format(self, entry):
return "\n%s\n" % self.wrap(super(TextwrapFormatter, self).format(entry))
self.logger = logging.getLogger(self.name)
self.logger.setLevel(logging.INFO)
log_file_name = "%s.log" % self.name
file_handler = logging.FileHandler(log_file_name)
file_handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)-8s %(message)s"))
self.logger.addHandler(file_handler)
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(TextwrapFormatter("%(levelname)s %(message)s"))
stream_handler.setLevel(logging.WARNING)
self.logger.addHandler(stream_handler)
def test_whitespace(self):
# Whitespace munging and end-of-sentence detection
text = """\
This is a paragraph that already has
line breaks. But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""
expect = ["This is a paragraph that already has line",
"breaks. But some of its lines are much",
"longer than the others, so it needs to be",
"wrapped. Some lines are tabbed too. What a",
"mess!"]
wrapper = TextWrapper(45, fix_sentence_endings=True)
result = wrapper.wrap(text)
self.check(result, expect)
result = wrapper.fill(text)
self.check(result, '\n'.join(expect))
def test_whitespace(self):
# Whitespace munging and end-of-sentence detection
text = """\
This is a paragraph that already has
line breaks. But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""
expect = ["This is a paragraph that already has line",
"breaks. But some of its lines are much",
"longer than the others, so it needs to be",
"wrapped. Some lines are tabbed too. What a",
"mess!"]
wrapper = TextWrapper(45, fix_sentence_endings=True)
result = wrapper.wrap(text)
self.check(result, expect)
result = wrapper.fill(text)
self.check(result, '\n'.join(expect))
def test_whitespace(self):
# Whitespace munging and end-of-sentence detection
text = """\
This is a paragraph that already has
line breaks. But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""
expect = ["This is a paragraph that already has line",
"breaks. But some of its lines are much",
"longer than the others, so it needs to be",
"wrapped. Some lines are tabbed too. What a",
"mess!"]
wrapper = TextWrapper(45, fix_sentence_endings=True)
result = wrapper.wrap(text)
self.check(result, expect)
result = wrapper.fill(text)
self.check(result, '\n'.join(expect))
def _split(self, text):
"""_split(text : string) -> [string]
Override original method that only split by 'wordsep_re'.
This '_split' split wide-characters into chunk by one character.
"""
def split(t):
return textwrap.TextWrapper._split(self, t)
chunks = []
for chunk in split(text):
for w, g in groupby(chunk, column_width):
if w == 1:
chunks.extend(split(''.join(g)))
else:
chunks.extend(list(g))
return chunks
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 wraptext(text, width=70, initial_indent='', subsequent_indent=''):
"""Simple wrapper around the ``textwrap.wrap`` function in the standard
library. This version does not wrap lines on hyphens in words.
:param text: the text to wrap
:param width: the maximum line width
:param initial_indent: string that will be prepended to the first line of
wrapped output
:param subsequent_indent: string that will be prepended to all lines save
the first of wrapped output
:return: a list of lines
:rtype: `list`
"""
wrapper = TextWrapper(width=width, initial_indent=initial_indent,
subsequent_indent=subsequent_indent,
break_long_words=False)
return wrapper.wrap(text)
def __init__(self, format=None, date_format=None, max_width=79):
"""
Initialize a new ``WrappingLogFormatter``.
:Parameters:
format : str
The format to use, or ``None`` for the logging default
date_format : str
Date format, or ``None`` for the logging default
max_width : int
Maximum line width, or ``None`` to default to 79./
"""
self.wrapper = textwrap.TextWrapper(width=max_width,
subsequent_indent=' ')
logging.Formatter.__init__(self, format, date_format)
def get_commit_messages_since(self, version):
"""Return a formatted list of commit messages since the given tagged version."""
tag = '{}.{}.{}'.format(*version)
output = util.communicate([
'git', 'log',
'--pretty=format:{{{{%w(0,0,0)%s %b}}}}',
'--reverse', tag + '..'
])
# Split the messages, they are bounded by {{{{ }}}}
messages = []
for match in self.COMMIT_MSG_RE.finditer(output):
messages.append(match.group(1).strip())
# Wrap the messages
wrapper = TextWrapper(initial_indent='- ', subsequent_indent=' ')
messages = list(map(lambda msg: '\n'.join(wrapper.wrap(msg)), messages))
return '\n\n'.join(messages) + '\n'
def text_to_image(msg, font=None, font_path=None, font_size=24, accurate=True):
font = font if font else ImageFont.truetype(font_path, font_size)
wrapper = textwrap.TextWrapper()
# w is the widest and y is the tallest
glyph_w, glyph_h = font.getsize('w')[0], font.getsize('y')[1]
chars_per_line = PRINTER_WIDTH / glyph_w
wrapper.width = chars_per_line
msg_lines = wrapper.wrap(msg)
# lines may vary in height so loop over all of them when accurate is True
# otherwise just count each line as the height of a 'y'
height = sum([font.getsize(h)[1] for h in msg_lines]) if accurate else glyph_h * len(msg_lines)
img = Image.new('1', (PRINTER_WIDTH, height), color='white')
draw = ImageDraw.Draw(img)
y = 0
for line in msg_lines:
h = font.getsize(line)[1]
draw.text([0, y], line, font=font)
y += h
return img
def print_report(self):
print "{0} {1}{0} :".format(cruftmoji.SPRUCE, self.name)
if self.description:
tab = "\t"
wrapper = textwrap.TextWrapper(
width=73, initial_indent=tab, subsequent_indent=tab)
print "\n".join(wrapper.wrap(self.description))
print
if self.items or self.metadata:
if self.items_keys:
for key, reverse in reversed(self.items_keys):
if key == "version":
self.items.sort(key=lambda v: LooseVersion(v[key]),
reverse=reverse)
else:
self.items.sort(key=itemgetter(key), reverse=reverse)
self._print_section("items")
self._print_section("metadata")
else:
print "\tNo items."
print
def test_whitespace(self):
# Whitespace munging and end-of-sentence detection
text = """\
This is a paragraph that already has
line breaks. But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""
expect = ["This is a paragraph that already has line",
"breaks. But some of its lines are much",
"longer than the others, so it needs to be",
"wrapped. Some lines are tabbed too. What a",
"mess!"]
wrapper = TextWrapper(45, fix_sentence_endings=True)
result = wrapper.wrap(text)
self.check(result, expect)
result = wrapper.fill(text)
self.check(result, '\n'.join(expect))
def listPlugins():
descStart = 21
pluginList = plugins.core.pluginModules.values()
sortedPlugins = sorted(pluginList, key=lambda x: x.name)
print("The following plugins are available:")
for plugin in sortedPlugins:
versionStr = "{0}.{1}.{2}".format(plugin.versionMajor, plugin.versionMinor, plugin.versionRevision)
headerText ="{0} ({1}):".format(plugin.name, versionStr)
rawText = "{0}\n{1}{2}".format(headerText, ' ' * (descStart - len(headerText)), plugin.description)
wrapper = textwrap.TextWrapper(initial_indent=' ', subsequent_indent = ' ' * (descStart + 3), width=78)
renderText = wrapper.wrap(rawText)
for line in renderText:
print(line)
print()
print("The following plugins are disabled (rename to enable): {0}".format(' '.join(plugins.modulesDisabled)))
# Parse arguments
def test_whitespace(self):
# Whitespace munging and end-of-sentence detection
text = """\
This is a paragraph that already has
line breaks. But some of its lines are much longer than the others,
so it needs to be wrapped.
Some lines are \ttabbed too.
What a mess!
"""
expect = ["This is a paragraph that already has line",
"breaks. But some of its lines are much",
"longer than the others, so it needs to be",
"wrapped. Some lines are tabbed too. What a",
"mess!"]
wrapper = TextWrapper(45, fix_sentence_endings=True)
result = wrapper.wrap(text)
self.check(result, expect)
result = wrapper.fill(text)
self.check(result, '\n'.join(expect))
def printInd(s, level=1, length=70, prefix=''):
from textwrap import TextWrapper
indents={1: 0, 2: 4, 3: 8, 4: 12, 5: 16}
ind=indents[level]
indstr=' '*int(ind)
wrapper=TextWrapper()
wrapper.width=length
wrapper.initial_indent=indstr
wrapper.subsequent_indent=indstr
string=wrapper.fill('%s %s' %(prefix,s))
try:
print('\n'+string)
except:
print('\n'+string.encode('ascii','replace'))
return
#-------------------Read in text file and store data-------------------
def __init__(self, screen, args):
self.log = logging.getLogger(__name__)
self.log.debug("Initializing curses screen.")
self.ctrlchars = (unicurses.KEY_RESIZE, unicurses.KEY_ENTER, ord('\n'), ord('\x1b'))
self.sslnoverify = sys.version_info >= (2, 7, 9) and args.ssl_no_verify
self.msg = None
self.screen = screen
self.state = DataTree(self, {})
self.oldstate = DataTree(self, {})
self.validate = Validate(self)
self.format = Format(self)
self.h, self.w = 22, 78
self.nexus = Nexus()
self.artifactory = Artifactory(self)
self.wrap = textwrap.TextWrapper(width=self.w - 1)
self.initattrs()
self.frame = unicurses.newwin(self.h + 2, self.w + 2, 0, 0)
unicurses.wborder(self.frame)
self.win = unicurses.newwin(self.h, self.w, 0, 0)
unicurses.keypad(self.win, 1)
self.log.debug("Curses screen initialized.")
def test_document_wrapper():
"""
Document Wrapper is deals with wrapping text with new lines already present.
:return:
"""
str3="0123456789\n0123456789\n01234567890123456789"
desired3="0123456789\n0123456789\n012345678901\n23456789"
w1 = textwrap.TextWrapper(width=12, replace_whitespace=False)
r1 = w1.fill(str3)
assert r1 != desired3
assert r1 == "0123456789\n0123456789\n0\n123456789012\n3456789"
w2 = DocumentWrapper(width=12, replace_whitespace=False)
r2 = w2.fill(str3)
assert r2 == desired3
def format_single_arg(config, line_width, arg):
"""Return a list of lines that reflow the single arg and all it's comments
into a block with width at most line_width."""
if arg.comments:
comment_stream = ' '.join([comment[1:].strip()
for comment in arg.comments])
initial_indent = arg.contents + ' # '
subsequent_indent = ' ' * len(arg.contents) + ' # '
wrapper = textwrap.TextWrapper(width=line_width,
expand_tabs=True,
replace_whitespace=True,
drop_whitespace=True,
initial_indent=initial_indent,
subsequent_indent=subsequent_indent)
return wrapper.wrap(comment_stream)
else:
return [arg.contents]
def __init__(self,
indent = '',
width = 0):
super().__init__()
self.reset()
self.strict = False
self.convert_charrefs = True
self.indent = indent
if width > 0:
self.wrap = TextWrapper()
self.wrap.initial_indent = indent
self.wrap.subsequent_indent = indent
self.wrap.width = width
else:
self.wrap = None
def _print_timeline(item):
def wrap_text(text, width):
wrapper = TextWrapper(width=width, break_long_words=False, break_on_hyphens=False)
return chain(*[wrapper.wrap(l) for l in text.split("\n")])
def timeline_rows(item):
name = item['name']
time = item['time'].strftime('%Y-%m-%d %H:%M%Z')
left_column = [name, time]
if 'reblogged' in item:
left_column.append(item['reblogged'])
text = item['text']
right_column = wrap_text(text, 80)
return zip_longest(left_column, right_column, fillvalue="")
for left, right in timeline_rows(item):
print_out("{:30} ? {}".format(left, right))
def set_history(self, rom_name, game_name):
"""display history for rom_name"""
if not self.histview_ok:
return
rom_name = rom_name.upper()
#display
self.lsHistory = []
if rom_name not in self.history:
self.lblHeading.set_text('no history found')
self.WinMain.show_window('history')
return
tw = textwrap.TextWrapper(width=self.line_length, replace_whitespace=False)
for line in self.history[rom_name]:
if line == ' ':
wrapped_lines = ['']
else:
wrapped_lines = tw.wrap(line)
for wl in wrapped_lines:
self.lsHistory.append(wl)
self.sclHistory.ls = self.lsHistory
self.lblHeading.set_text(game_name)
self.sclHistory.set_selected(0)
self.WinMain.show_window('history')
def help_checkers():
import pyomo.environ
import pyomo.util.plugin
from pyomo.checker import IModelChecker
wrapper = textwrap.TextWrapper()
wrapper.initial_indent = ' '
wrapper.subsequent_indent = ' '
print("")
print("Pyomo Model Checkers")
print("--------------------")
ep = pyomo.util.plugin.ExtensionPoint(IModelChecker)
tmp = {}
for checker in ep.extensions():
for alias in getattr(checker, '_factory_aliases', set()):
tmp[alias[0]] = alias[1]
for key in sorted(tmp.keys()):
print(" "+key)
print(wrapper.fill(tmp[key]))
def fping(self, cmd):
print("{i} {c}".format(i=ctinfo, c=' '.join(cmd)))
logging.info(' '.join(cmd))
command = subprocess.run(cmd, stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL, universal_newlines=True, shell=False)
wrapper = TextWrapper(initial_indent="{i} ".format(i=ctinfo),
subsequent_indent="{i} ".format(i=ctinfo))
if len(command.stdout.split("\n")) > 2:
output = wrapper.fill(command.stdout.replace("\n", ", "))
output = output.rstrip(',')
# TODO: write a function for this (in misc maybe) that cleans the target
# and adds it if not a hostname (hostnames will be resolved & IP's added)
for host in command.stdout.split("\n"):
self.up_targets_dict.append(host)
elif len(command.stdout.split("\n")) > 1:
output = wrapper.fill(command.stdout.strip("\n"))
for host in command.stdout.split("\n"):
self.up_targets_dict.append(host)
else:
output = wrapper.fill("No Response")
print(output)
logging.info("Results: {r}".format(r=command.stdout.replace("\n", ", ")))
def main( ):
parser = get_opt_parser( )
opts = parser.parse_args( )
tw_opts = {
'width': 50,
'subsequent_indent': ' ',
'initial_indent': ' ',
}
wrapper = textwrap.TextWrapper(**tw_opts)
for stream in opts.infile:
print "## START %s" % (stream.name)
records = find_dates(stream)
i = 0
for record in records:
prefix = '#### RECORD {} {}'.format(i, str(record))
# record.pformat(prefix)
i += 1
print "`end %s: %s records`" % (stream.name, len(records))
stream.close( )
def wraptext(text, width=70, initial_indent='', subsequent_indent=''):
"""Simple wrapper around the ``textwrap.wrap`` function in the standard
library. This version does not wrap lines on hyphens in words.
:param text: the text to wrap
:param width: the maximum line width
:param initial_indent: string that will be prepended to the first line of
wrapped output
:param subsequent_indent: string that will be prepended to all lines save
the first of wrapped output
"""
wrapper = TextWrapper(width=width, initial_indent=initial_indent,
subsequent_indent=subsequent_indent,
break_long_words=False)
return wrapper.wrap(text)
def fill(text, indent, heading=None):
sub = indent * " "
if heading:
init = (indent - 2) * " " + heading + " -- "
else:
init = sub
w = textwrap.TextWrapper(initial_indent=init, subsequent_indent=sub)
return w.fill(" ".join(text.split()))
def _readbinary(self, fmt, numbytes):
"""
Private method that unpack n bytes of data using format <fmt>.
It returns a tuple or a mixed value if the tuple length is 1.
"""
bytes = self.fhandle.read(numbytes)
tup = struct.unpack(fmt, bytes)
if len(tup) == 1:
return tup[0]
return tup
# }}}
# class TextWrapper {{{