Python textwrap 模块,TextWrapper() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用textwrap.TextWrapper()

项目:HTP    作者:nklose    | 项目源码 | 文件源码
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
项目:sublime-text-3-packages    作者:nickjj    | 项目源码 | 文件源码
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'
项目:XimaExport    作者:ryankomodo    | 项目源码 | 文件源码
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-------------------
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
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)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
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))
项目:oil    作者:oilshell    | 项目源码 | 文件源码
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))
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
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))
项目:chalktalk_docs    作者:loremIpsum1771    | 项目源码 | 文件源码
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
项目:linotype    作者:lostatc    | 项目源码 | 文件源码
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)
项目:ome-model    作者:ome    | 项目源码 | 文件源码
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)
项目:My-Web-Server-Framework-With-Python2.7    作者:syjsu    | 项目源码 | 文件源码
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)
项目:sublimeTextConfig    作者:luoye-fe    | 项目源码 | 文件源码
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'
项目:paperwaster    作者:Talon876    | 项目源码 | 文件源码
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
项目:Spruce-for-Munki    作者:sheagcraig    | 项目源码 | 文件源码
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
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
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))
项目:paladin-plugins    作者:twestbrookunh    | 项目源码 | 文件源码
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
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
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))
项目:Menotexport    作者:Xunius    | 项目源码 | 文件源码
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-------------------
项目:nexus2artifactory    作者:JFrogDev    | 项目源码 | 文件源码
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.")
项目:artemis    作者:QUVA-Lab    | 项目源码 | 文件源码
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
项目:cmake_format    作者:cheshirekow    | 项目源码 | 文件源码
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]
项目:tootstream    作者:magicalraccoon    | 项目源码 | 文件源码
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
项目:toot    作者:ihabunek    | 项目源码 | 文件源码
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))
项目:wahcade    作者:sairuk    | 项目源码 | 文件源码
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')
项目:pyomo    作者:Pyomo    | 项目源码 | 文件源码
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]))
项目:faze    作者:KhasMek    | 项目源码 | 文件源码
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", ", ")))
项目:decocare    作者:openaps    | 项目源码 | 文件源码
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( )
项目:sndlatr    作者:Schibum    | 项目源码 | 文件源码
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)
项目:txamqp    作者:txamqp    | 项目源码 | 文件源码
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()))
项目:KodiDevKit    作者:phil65    | 项目源码 | 文件源码
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 {{{
项目:KodiDevKit    作者:phil65    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        drop_whitespace = kwargs.pop('drop_whitespace', True)
        textwrap.TextWrapper.__init__(self, *args, **kwargs)
        self.drop_whitespace = drop_whitespace
项目:KodiDevKit    作者:phil65    | 项目源码 | 文件源码
def wrap(text, width=70, **kwargs):
    """
    Wrap a single paragraph of text, returning a list of wrapped lines.
    """
    if sys.version_info < (2, 6):
        return TextWrapper(width=width, **kwargs).wrap(text)
    return textwrap.wrap(text, width=width, **kwargs)

# }}}
项目:psyplot    作者:Chilipp    | 项目源码 | 文件源码
def show_summaries(cls, keys=None, indent=0, *args, **kwargs):
        """
        Classmethod to print the summaries of the formatoptions

        Parameters
        ----------
        %(Plotter.show_keys.parameters)s

        Other Parameters
        ----------------
        %(Plotter.show_keys.other_parameters)s

        Returns
        -------
        %(Plotter.show_keys.returns)s

        See Also
        --------
        show_keys, show_docs"""
        def find_summary(key, key_txt, doc):
            return '\n'.join(wrapper.wrap(doc[:doc.find('\n\n')]))
        str_indent = " " * indent
        wrapper = TextWrapper(width=80, initial_indent=str_indent + ' ' * 4,
                              subsequent_indent=str_indent + ' ' * 4)
        return cls._show_doc(find_summary, keys=keys, indent=indent,
                             *args, **kwargs)
项目:aws-cfn-plex    作者:lordmuffin    | 项目源码 | 文件源码
def my_wrap(text, width=MAXWIDTH, **kwargs):
    w = TextWrapper(width=width, **kwargs)
    return w.wrap(text)
项目:XimaExport    作者:ryankomodo    | 项目源码 | 文件源码
def printHeader(s, level=1, length=70, prefix='# <XimaExport>:'):
    from textwrap import TextWrapper

    decs={1: '=', 2: '-', 3: '.'}
    indents={1: 0, 2: 4, 3: 8}

    dec=decs[level]
    ind=indents[level]
    indstr=' '*int(ind)

    wrapper=TextWrapper()
    wrapper.width=length-ind
    wrapper.initial_indent=indstr
    wrapper.subsequent_indent=indstr

    #-------------Get delimiter line-------------
    hline='%s%s' %(' '*int(ind),dec*int(length-ind)) 

    #--------------------Wrap texts--------------------
    strings=wrapper.wrap('%s %s' %(prefix,s))

    #----------------------Print----------------------
    try:
        print('\n'+hline)
    except:
        print('\n'+hline.encode('ascii','replace'))
    for ss in strings:
        try:
            print(ss)
        except:
            print(ss.encode('ascii','replace'))
    #print(hline)

    return
项目:XimaExport    作者:ryankomodo    | 项目源码 | 文件源码
def printNumHeader(s, idx, num, level=1, length=70, prefix='# <XimaExport>:'):
    from textwrap import TextWrapper

    decs={1: '=', 2: '-', 3: '.'}
    indents={1: 0, 2: 4, 3: 8}

    dec=decs[level]
    ind=indents[level]
    indstr=' '*int(ind)

    wrapper=TextWrapper()
    wrapper.width=length-ind
    wrapper.initial_indent=indstr
    wrapper.subsequent_indent=indstr

    #-------------Get delimiter line-------------
    decl=int((length-ind-2-len(str(idx))-len(str(num)))/2.)
    decl=decl*dec

    hline1='%s%s %d/%d %s' %(' '*int(ind),decl,idx,num,decl) 
    #hline2='%s%s' %(' '*int(ind),dec*int(length-ind)) 

    #--------------------Wrap texts--------------------
    strings=wrapper.wrap('%s %s' %(prefix,s))

    #----------------------Print----------------------
    try:
        print('\n'+hline1)
    except:
        print('\n'+hline1.encode('ascii','replace'))
    for ss in strings:
        try:
            print(ss)
        except:
            print(ss.encode('ascii','replace'))
    #print(hline2)

    return
项目:plasmidtron    作者:sanger-pathogens    | 项目源码 | 文件源码
def create_file(self):
        self.logger.warning("Creating file with methods")
        wrapper = TextWrapper()
        with open(self.filename, 'w') as output_fileh:
            output_fileh.write('Method\n')

            output_fileh.write(wrapper.fill(self.methods_paragraph(len(self.trait_samples),len(self.nontrait_samples), self.plasmidtron_version(),self.kmc_version(), self.min_kmers_threshold, self.spades_version(), self.min_contig_length, self.running_time() )))

            output_fileh.write('\n\nReferences\n')
            output_fileh.write(wrapper.fill(self.references_paragraph()))
项目:AshsSDK    作者:thehappydinoa    | 项目源码 | 文件源码
def my_wrap(text, width=MAXWIDTH, **kwargs):
    w = TextWrapper(width=width, **kwargs)
    return w.wrap(text)
项目:pymzn    作者:paolodragone    | 项目源码 | 文件源码
def _get_wrapper():
    global _wrapper
    if not _wrapper:
        _wrapper = TextWrapper(width=config.get('dzn_width', 70),
                               subsequent_indent=' '*4, break_long_words=False,
                               break_on_hyphens = False)
    return _wrapper
项目:coquery    作者:gkunter    | 项目源码 | 文件源码
def build_initialize(self):
        """
        Initialize the corpus build.
        """

        self.start_time = time.time()
        self.logger.info("--- Starting ---")
        self.logger.info("Building corpus %s" % self.name)
        self.logger.info("Command line arguments: %s" % " ".join(sys.argv[1:]))
        if not self._widget:
            print("\n%s\n" % textwrap.TextWrapper(width=79).fill(" ".join(self.get_description())))

        # Corpus installers may require additional modules. For example,
        # Gabra is currently distributed as MongoDB files, which are read by
        # using the pymongo library.
        # Unless the user wishes to install only the corpus module, try to
        # import these additional modules, and raise an exception if they are
        # unavailable:
        if not self.arguments.only_module:
            for module, package, url in self.get_modules():
                try:
                    exec("import {}".format(module))
                except ImportError:
                    raise DependencyError(package, url)

        if self.DB.db_type == SQL_MYSQL:
            self.DB.connection.execute("SET NAMES 'utf8'")
            self.DB.connection.execute("SET CHARACTER SET 'utf8mb4'")
            self.DB.connection.execute("SET unique_checks=0")
            self.DB.connection.execute("SET foreign_key_checks=0")
项目:soapy_power    作者:xmikos    | 项目源码 | 文件源码
def wrap(text, indent='    '):
    """Wrap text to terminal width with default indentation"""
    wrapper = textwrap.TextWrapper(
        width=int(os.environ.get('COLUMNS', 80)),
        initial_indent=indent,
        subsequent_indent=indent
    )
    return '\n'.join(wrapper.wrap(text))
项目:pando-core    作者:DLR-RY    | 项目源码 | 文件源码
def _packet_parameter(self, parameter, elements):
        if isinstance(parameter, model.List):
            for p in parameter.parameters:
                self._packet_parameter(p, elements)
        else:
            wrapper = textwrap.TextWrapper()
            wrapper.width = 14

            text = wrapper.wrap(parameter.name)

            texts = []
            offset = (40 - self.text_height * len(text)) / 2 - 3
            for t in text:
                offset += self.text_height
                texts.append({
                    'text': t,
                    'y': offset,
                })

            elements.append({
                'type': 'element',
                'parameterName': texts,
                'parameterType': str(parameter.type),
                'parameterWidth': parameter.type.width,
                'x': self.state.x,
                'width': self.box_width,
            })
            self.state.x += self.box_width
            self.state.element_count += 1

            if isinstance(parameter, model.Repeater):
                self._packet_repeater(parameter, elements)
项目:rhsecapi    作者:ryran    | 项目源码 | 文件源码
def _set_cve_plaintext_width(self, wrapWidth):
        if wrapWidth == 1:
            if sys.stdin.isatty():
                wrapWidth = self._get_terminal_width() - 2
            else:
                logger.warning("Stdin redirection suppresses term-width auto-detection; setting WIDTH to 70")
                wrapWidth = 70
        if wrapWidth:
            self.wrapper = textwrap.TextWrapper(width=wrapWidth, initial_indent="   ", subsequent_indent="   ", replace_whitespace=False)
        else:
            self.wrapper = 0
        logger.debug("Set wrapWidth to '{0}'".format(wrapWidth))
项目:boartty    作者:openstack    | 项目源码 | 文件源码
def formatReply(self):
        text = self.comment_text
        pgraphs = []
        pgraph_accumulator = []
        wrap = True
        for line in text.split('\n'):
            if line.startswith('> '):
                wrap = False
                line = '> ' + line
            if not line:
                if pgraph_accumulator:
                    pgraphs.append((wrap, '\n'.join(pgraph_accumulator)))
                    pgraph_accumulator = []
                    wrap = True
                continue
            pgraph_accumulator.append(line)
        if pgraph_accumulator:
            pgraphs.append((wrap, '\n'.join(pgraph_accumulator)))
            pgraph_accumulator = []
            wrap = True
        wrapper = textwrap.TextWrapper(initial_indent='> ',
                                       subsequent_indent='> ')
        wrapped_pgraphs = []
        for wrap, pgraph in pgraphs:
            if wrap:
                wrapped_pgraphs.append('\n'.join(wrapper.wrap(pgraph)))
            else:
                wrapped_pgraphs.append(pgraph)
        return '\n>\n'.join(wrapped_pgraphs)
项目:inter    作者:rsms    | 项目源码 | 文件源码
def renameConfigFile(config, filename, newNames, dryRun=False, print=print):
  wrapper = TextWrapper()
  wrapper.width = 80
  wrapper.break_long_words = False
  wrapper.break_on_hyphens = False

  wrap = lambda names: '\n'.join(wrapper.wrap(' '.join(names)))

  didRename = False
  for propertyName, values in config.items('glyphs'):
    glyphNames = values.split()
    # print(propertyName, glyphNames)
    propChanged = False
    for name in glyphNames:
      if name in newNames:
        sectionChanged = True
    if sectionChanged:
      config.set('glyphs', propertyName, wrap(glyphNames)+'\n')
      didRename = True

    # config.set(section, option, value)
  if didRename:
    s = StringIO()
    config.write(s)
    s = s.getvalue()
    s = re.sub(r'\n(\w+)\s+=\s*', '\n\\1: ', s, flags=re.M)
    s = re.sub(r'((?:^|\n)\[[^\]]*\])', '\\1\n', s, flags=re.M)
    s = re.sub(r'\n\t\n', '\n\n', s, flags=re.M)
    s = s.strip() + '\n'
    print('Writing', filename)
    if not dryRun:
      with open(filename, 'w') as f:
        f.write(s)
项目:inter    作者:rsms    | 项目源码 | 文件源码
def updateConfigFile(config, filename, rmnames):
  wrapper = TextWrapper()
  wrapper.width = 80
  wrapper.break_long_words = False
  wrapper.break_on_hyphens = False
  wrap = lambda names: '\n'.join(wrapper.wrap(' '.join(names)))

  didChange = False

  for propertyName, values in config.items('glyphs'):
    glyphNames = values.split()
    propChanged = False
    glyphNames2 = [name for name in glyphNames if name not in rmnames]
    if len(glyphNames2) < len(glyphNames):
      print('[fontbuild.cfg] updating glyphs property', propertyName)
      config.set('glyphs', propertyName, wrap(glyphNames2)+'\n')
      didChange = True

  if didChange:
    s = StringIO()
    config.write(s)
    s = s.getvalue()
    s = re.sub(r'\n(\w+)\s+=\s*', '\n\\1: ', s, flags=re.M)
    s = re.sub(r'((?:^|\n)\[[^\]]*\])', '\\1\n', s, flags=re.M)
    s = re.sub(r'\n\t\n', '\n\n', s, flags=re.M)
    s = s.strip() + '\n'
    print('Writing', filename)
    if not dryRun:
      with open(filename, 'w') as f:
        f.write(s)
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def __get_text_wrapper(width=60):
    """
    Get text wrapper with a fixed with.

    :param width: width of the wrapper. Default 60.
    :return: text wrapper
    :rtype: :py:class:`TextWrapper`
    """
    wrapper = TextWrapper()
    wrapper.width = width
    wrapper.subsequent_indent = " "

    return wrapper
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def dump_recursive_parents(rpc,
                           post_author,
                           post_permlink,
                           limit=1,
                           format="markdown"):
    global currentThreadDepth

    limit = int(limit)

    postWrapper = TextWrapper()
    postWrapper.width = 120
    postWrapper.initial_indent = "  " * (limit)
    postWrapper.subsequent_indent = "  " * (limit)

    if limit > currentThreadDepth:
        currentThreadDepth = limit + 1

    post = rpc.get_content(post_author, post_permlink)

    if limit and post["parent_author"]:
        parent = rpc.get_content_replies(post["parent_author"], post["parent_permlink"])
        if len(parent):
            dump_recursive_parents(rpc, post["parent_author"], post["parent_permlink"], limit - 1)

    meta = {}
    for key in ["author", "permlink"]:
        meta[key] = post[key]
    meta["reply"] = "@{author}/{permlink}".format(**post)
    if format == "markdown":
        body = markdownify(post["body"])
    else:
        body = post["body"]
    yaml = frontmatter.Post(body, **meta)
    print(frontmatter.dumps(yaml))
项目:sweetshot    作者:AnCh7    | 项目源码 | 文件源码
def dump_recursive_comments(rpc,
                            post_author,
                            post_permlink,
                            depth=0,
                            format="markdown"):
    global currentThreadDepth
    postWrapper = TextWrapper()
    postWrapper.width = 120
    postWrapper.initial_indent = "  " * (depth + currentThreadDepth)
    postWrapper.subsequent_indent = "  " * (depth + currentThreadDepth)

    depth = int(depth)

    posts = rpc.get_content_replies(post_author, post_permlink)
    for post in posts:
        meta = {}
        for key in ["author", "permlink"]:
            meta[key] = post[key]
        meta["reply"] = "@{author}/{permlink}".format(**post)
        if format == "markdown":
            body = markdownify(post["body"])
        else:
            body = post["body"]
        yaml = frontmatter.Post(body, **meta)
        print(frontmatter.dumps(yaml))
        reply = rpc.get_content_replies(post["author"], post["permlink"])
        if len(reply):
            dump_recursive_comments(rpc, post["author"], post["permlink"], depth + 1)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def setUp(self):
        self.wrapper = TextWrapper(width=45)