python类fill()的实例源码

test_textwrap.py 文件源码 项目:python2-tracer 作者: extremecoders-re 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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!
gprof2dot.py 文件源码 项目:autoinjection 作者: ChengWiLL 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def wrap_function_name(self, name):
        """Split the function name on multiple lines."""

        if len(name) > 32:
            ratio = 2.0/3.0
            height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
            width = max(len(name)/height, 32)
            # TODO: break lines in symbols
            name = textwrap.fill(name, width, break_long_words=False)

        # Take away spaces
        name = name.replace(", ", ",")
        name = name.replace("> >", ">>")
        name = name.replace("> >", ">>") # catch consecutive

        return name
utils.py 文件源码 项目:tRNA-seq-tools 作者: merenlab 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def store_dict_as_FASTA_file(d, output_file_path, report_unique_sequences=False, wrap_from=200):
    filesnpaths.is_output_file_writable(output_file_path)
    output = open(output_file_path, 'w')

    props_h = sorted(list(list(d.values())[0]['props'].keys()))

    if report_unique_sequences:
        seqs_sorted_by_frequency = [x[1] for x in sorted([(len(d[seq]['ids']), seq) for seq in d], reverse=True)]

        for seq in seqs_sorted_by_frequency:
            frequency = len(d[seq]['ids'])
            seq_id = d[seq]['ids'].pop()
            output.write('>%s %s|frequency:%d\n' % (seq_id, '|'.join(['%s:%s' % (t[0], t[1]) for t in d[seq]['props'].items()]), frequency))
            output.write('%s\n' % textwrap.fill(seq, wrap_from, break_on_hyphens=False))
    else:
        for seq in d:
            props = '|'.join(['%s:%s' % (t[0], t[1]) for t in d[seq]['props'].items()])
            for seq_id in d[seq]['ids']:
                output.write('>%s %s\n' % (seq_id, props))
                output.write('%s\n' % textwrap.fill(seq, wrap_from, break_on_hyphens=False))

    output.close()
    return True
function.py 文件源码 项目:ecodash 作者: Servir-Mekong 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def __str__(self):
    """Returns a user-readable docstring for this function."""
    DOCSTRING_WIDTH = 75
    signature = self.getSignature()
    parts = []
    if 'description' in signature:
      parts.append(
          textwrap.fill(signature['description'], width=DOCSTRING_WIDTH))
    args = signature['args']
    if args:
      parts.append('')
      parts.append('Args:')
      for arg in args:
        name_part = '  ' + arg['name']
        if 'description' in arg:
          name_part += ': '
          arg_header = name_part + arg['description']
        else:
          arg_header = name_part
        arg_doc = textwrap.fill(arg_header,
                                width=DOCSTRING_WIDTH - len(name_part),
                                subsequent_indent=' ' * 6)
        parts.append(arg_doc)
    return u'\n'.join(parts).encode('utf8')
test_textwrap.py 文件源码 项目:web_ctp 作者: molebot 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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!
askpass_client.py 文件源码 项目:pssh 作者: lilydjwg 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def executable_path():
    """Determines the value to use for SSH_ASKPASS.

    The value is cached since this may be called many times.
    """
    global _executable_path
    if _executable_path is None:
        for path in ASKPASS_PATHS:
            if os.access(path, os.X_OK):
                _executable_path = path
                break
        else:
            _executable_path = ''
            sys.stderr.write(textwrap.fill("Warning: could not find an"
                    " executable path for askpass because PSSH was not"
                    " installed correctly.  Password prompts will not work."))
            sys.stderr.write('\n')
    return _executable_path
askpass_server.py 文件源码 项目:pssh 作者: lilydjwg 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def start(self, iomap, backlog):
        """Prompts for the password, creates a socket, and starts listening.

        The specified backlog should be the max number of clients connecting
        at once.
        """
        message = ('Warning: do not enter your password if anyone else has'
                ' superuser privileges or access to your account.')
        print(textwrap.fill(message))

        self.password = getpass.getpass()

        # Note that according to the docs for mkdtemp, "The directory is
        # readable, writable, and searchable only by the creating user."
        self.tempdir = tempfile.mkdtemp(prefix='pssh.')
        self.address = os.path.join(self.tempdir, 'pssh_askpass_socket')
        self.sock = socket.socket(socket.AF_UNIX)
        psshutil.set_cloexec(self.sock)
        self.sock.bind(self.address)
        self.sock.listen(backlog)
        iomap.register_read(self.sock.fileno(), self.handle_listen)
gprof2dot.py 文件源码 项目:TF_Deformable_Net 作者: Zardinality 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def wrap_function_name(self, name):
        """Split the function name on multiple lines."""

        if len(name) > 32:
            ratio = 2.0/3.0
            height = max(int(len(name)/(1.0 - ratio) + 0.5), 1)
            width = max(len(name)/height, 32)
            # TODO: break lines in symbols
            name = textwrap.fill(name, width, break_long_words=False)

        # Take away spaces
        name = name.replace(", ", ",")
        name = name.replace("> >", ">>")
        name = name.replace("> >", ">>") # catch consecutive

        return name
_make.py 文件源码 项目:deb-python-rjsmin 作者: openstack 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def print_help(self):
        """ Print make help """
        import textwrap as _textwrap

        targets = self.targetinfo()
        keys = []
        for key, info in targets.items():
            if not info['hide']:
                keys.append(key)
        keys.sort()
        length = max(map(len, keys))
        info = []
        for key in keys:
            info.append("%s%s" % (
                (key + " " * length)[:length + 2],
                _textwrap.fill(
                    targets[key]['desc'].strip(),
                    subsequent_indent=" " * (length + 2)
                ),
            ))
        print "Available targets:\n\n" + "\n".join(info)
_make.py 文件源码 项目:deb-python-rjsmin 作者: openstack 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def print_help(self):
        """ Print make help """
        import textwrap as _textwrap

        targets = self.targetinfo()
        keys = []
        for key, info in list(targets.items()):
            if not info['hide']:
                keys.append(key)
        keys.sort()
        length = max(list(map(len, keys)))
        info = []
        for key in keys:
            info.append("%s%s" % (
                (key + " " * length)[:length + 2],
                _textwrap.fill(
                    targets[key]['desc'].strip(),
                    subsequent_indent=" " * (length + 2)
                ),
            ))
        print("Available targets:\n\n" + "\n".join(info))
verbnet.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def pprint_subclasses(self, vnclass, indent=''):
        """
        Return a string containing a pretty-printed representation of
        the given verbnet class's subclasses.

        :param vnclass: A verbnet class identifier; or an ElementTree
            containing the xml contents of a verbnet class.
        """
        if isinstance(vnclass, compat.string_types):
            vnclass = self.vnclass(vnclass)

        subclasses = [subclass.get('ID') for subclass in
                      vnclass.findall('SUBCLASSES/VNSUBCLASS')]
        if not subclasses: subclasses = ['(none)']
        s = 'Subclasses: ' + ' '.join(subclasses)
        return textwrap.fill(s, 70, initial_indent=indent,
                             subsequent_indent=indent+'  ')
verbnet.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def pprint_members(self, vnclass, indent=''):
        """
        Return a string containing a pretty-printed representation of
        the given verbnet class's member verbs.

        :param vnclass: A verbnet class identifier; or an ElementTree
            containing the xml contents of a verbnet class.
        """
        if isinstance(vnclass, compat.string_types):
            vnclass = self.vnclass(vnclass)

        members = [member.get('name') for member in
                   vnclass.findall('MEMBERS/MEMBER')]
        if not members: members = ['(none)']
        s = 'Members: ' + ' '.join(members)
        return textwrap.fill(s, 70, initial_indent=indent,
                             subsequent_indent=indent+'  ')
internals.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def _add_epytext_field(obj, field, message):
    """Add an epytext @field to a given object's docstring."""
    indent = ''
    # If we already have a docstring, then add a blank line to separate
    # it from the new field, and check its indentation.
    if obj.__doc__:
        obj.__doc__ = obj.__doc__.rstrip()+'\n\n'
        indents = re.findall(r'(?<=\n)[ ]+(?!\s)', obj.__doc__.expandtabs())
        if indents: indent = min(indents)
    # If we don't have a docstring, add an empty one.
    else:
        obj.__doc__ = ''

    obj.__doc__ += textwrap.fill('@%s: %s' % (field, message),
                                 initial_indent=indent,
                                 subsequent_indent=indent+'    ')
brill_trainer.py 文件源码 项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda 作者: SignalMedia 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _trace_rule(self, rule):
        assert self._rule_scores[rule] == sum(self._positions_by_rule[rule].values())

        changes = self._positions_by_rule[rule].values()
        num_fixed = len([c for c in changes if c == 1])
        num_broken = len([c for c in changes if c == -1])
        num_other = len([c for c in changes if c == 0])
        score = self._rule_scores[rule]

        rulestr = rule.format(self._ruleformat)
        if self._trace > 2:
            print('%4d%4d%4d%4d  |' % (score, num_fixed, num_broken, num_other), end=' ')
            print(textwrap.fill(rulestr, initial_indent=' '*20, width=79,
                                subsequent_indent=' '*18+'|   ').strip())
        else:
            print(rulestr)
iam_commandhelper.py 文件源码 项目:orca 作者: bdastur 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def display_iam_user_permissions_table(self,
                                           user_name,
                                           profile_perms):
        '''
        Display tabular format
        '''
        table = prettytable.PrettyTable()
        table.add_column("User Name", [user_name])

        for profile in profile_perms.keys():
            if profile_perms[profile] is None:
                continue

            statementstr = ""
            for statement in profile_perms[profile]:
                resources = statement['Resource']
                actions = statement.get('Action', None)
                if not actions:
                    actions = statement.get('NotAction', None)
                effect = statement['Effect']

                #statementstr = statementstr + "-" * 29 + "\n"

                tempstr = "Resources: " + str(resources)
                statementstr = statementstr + self.fillstr(tempstr, 30)

                tempstr = "Actions: " + \
                    str(actions)
                statementstr = statementstr + self.fillstr(tempstr, 30)

                tempstr = "Effect: " + \
                    str(effect)
                statementstr = statementstr + self.fillstr(tempstr, 30)
                statementstr = statementstr + "-" * 29 + "\n"

            statementstr = textwrap.fill(statementstr, 34)
            table.add_column(profile, [statementstr], align="l")

        print table
iam_commandhelper.py 文件源码 项目:orca 作者: bdastur 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def display_iam_user_policies_table(self,
                                        user_name,
                                        policyinfo):
        '''
        Display user policy info in tabular format
        '''
        table = prettytable.PrettyTable()
        table.add_column("User Name", [user_name])

        for profile in policyinfo.keys():

            if policyinfo[profile] is None:
                continue

            policystr = ""
            for policy in policyinfo[profile]:
                policyname = policy['PolicyName']
                policy_type = policy['type']

                tempstr = "Name: " + policyname
                policystr = policystr + self.fillstr(tempstr, 30)
                tempstr = "Type: " + policy_type
                policystr = policystr + self.fillstr(tempstr, 30)

            policystr = textwrap.fill(policystr, 34)
            table.add_column(profile, [policystr], align="l")

        print table
optparse.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _format_text(self, text):
        """
        Format a paragraph of free-form text for inclusion in the
        help output at the current indentation level.
        """
        text_width = self.width - self.current_indent
        indent = " "*self.current_indent
        return textwrap.fill(text,
                             text_width,
                             initial_indent=indent,
                             subsequent_indent=indent)


问题


面经


文章

微信
公众号

扫码关注公众号