当前位置: 首页>>代码示例>>Python>>正文


Python textwrap.fill函数代码示例

本文整理汇总了Python中textwrap.fill函数的典型用法代码示例。如果您正苦于以下问题:Python fill函数的具体用法?Python fill怎么用?Python fill使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了fill函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: display_pull_request

def display_pull_request(pull_request):
	"""Nicely display_pull_request info about a given pull request"""

	display_pull_request_minimal(pull_request)

	description_indent = options['description-indent']

	print "%s%s" % (description_indent, color_text(pull_request.get('html_url'), 'display-title-url'))

	pr_body = pull_request.get('body')

	if pr_body and pr_body.strip():
		pr_body = re.sub('(<br\s?/?>)', '\n', pr_body.strip())

		if options['description-strip-newlines']:
			pr_body = fill(pr_body, initial_indent=description_indent, subsequent_indent=description_indent, width=80)
		else:
			# Normalize newlines
			pr_body = re.sub('\r?\n', '\n', pr_body)

			pr_body = pr_body.splitlines()

			pr_body = [fill(line.strip(), initial_indent=description_indent, subsequent_indent=description_indent, width=80) for line in pr_body]

			pr_body = '\n'.join(pr_body)

		print pr_body

	print
开发者ID:JoyceWang08211,项目名称:git-tools,代码行数:29,代码来源:git-pull-request.py

示例2: get_env

def get_env(suppress_warning=False):
    '''
    :returns env_vars: mapping of environment variable names to resolved values
    :type env_vars: dict

    This method looks up the known environment variables, and if they
    are not found, then attempts to resolve them by looking in the
    file ~/.dnanexus_config/environment, followed by the installed
    defaults in /opt/dnanexus/environment.
    '''

    env_vars = read_conf_dir(get_global_conf_dir())
    env_vars.update(read_conf_dir(get_user_conf_dir()))
    env_vars.update(read_conf_dir(get_session_conf_dir()))
    env_overrides = []
    for var in VAR_NAMES:
        if var in os.environ:
            if var in env_vars and env_vars.get(var) != os.environ[var]:
                env_overrides.append(var)
            env_vars[var] = os.environ[var]
        elif var not in env_vars:
            env_vars[var] = None

    if sys.stdout.isatty():
        if not suppress_warning and len(env_overrides) > 0:
            sys.stderr.write(textwrap.fill("WARNING: The following environment variables were found to be different than the values last stored by dx: " + ", ".join(env_overrides), width=80) + '\n')
            sys.stderr.write(textwrap.fill('To use the values stored by dx, unset the environment variables in your shell by running "source ~/.dnanexus_config/unsetenv".  To clear the dx-stored values, run "dx clearenv".', width=80) + '\n')

    return env_vars
开发者ID:paulmm,项目名称:dx-toolkit,代码行数:29,代码来源:env.py

示例3: show_plugin

 def show_plugin(self, plugin):
     self.showing_widget = plugin.create_widget(self.scroll_area)
     self.showing_widget.genesis(self.gui)
     self.showing_widget.initialize()
     self.set_tooltips_for_labels()
     self.scroll_area.setWidget(self.showing_widget)
     self.stack.setCurrentIndex(1)
     self.showing_widget.show()
     self.setWindowTitle(__appname__ + ' - ' + _('Preferences') + ' - ' +
             plugin.gui_name)
     self.apply_action.setEnabled(False)
     self.showing_widget.changed_signal.connect(lambda :
             self.apply_action.setEnabled(True))
     self.restore_action.setEnabled(self.showing_widget.supports_restoring_to_defaults)
     tt = self.showing_widget.restore_defaults_desc
     if not self.restore_action.isEnabled():
         tt = _('Restoring to defaults not supported for') + ' ' + \
             plugin.gui_name
     self.restore_action.setToolTip(textwrap.fill(tt))
     self.restore_action.setWhatsThis(textwrap.fill(tt))
     self.restore_action.setStatusTip(tt)
     self.bar_title.show_plugin(plugin)
     self.setWindowIcon(QIcon(plugin.icon))
     self.bar.setVisible(True)
     self.bb.setVisible(False)
开发者ID:Eksmo,项目名称:calibre,代码行数:25,代码来源:main.py

示例4: repo_status

def repo_status(repo, tracking_branch, remote_ref, indent=0):
  # Make sure the right branch is checked out
  if repo.current_branch() != tracking_branch:
    print " " * indent + ("Checked out branch is %s instead of %s" %
                         (repo.current_branch(), tracking_branch))

  # Make sure the branches exist
  has_tracking = repo.has_ref(tracking_branch)
  has_remote = repo.has_ref(remote_ref)

  if not has_tracking:
    print " " * indent + "You appear to be missing the tracking branch " + \
          tracking_branch
  if not has_remote:
    print " " * indent + "You appear to be missing the remote branch " + \
          remote_ref

  if not has_tracking or not has_remote:
    return

  # Print tracking branch status
  (left, right) = repo.tracking_status(tracking_branch, remote_ref)
  text = _format_tracking(tracking_branch, remote_ref, left, right)
  indent_str = " " * indent
  print textwrap.fill(text, initial_indent=indent_str, subsequent_indent=indent_str)
开发者ID:philz,项目名称:crepo,代码行数:25,代码来源:crepo.py

示例5: promptForLogicalInfo

def promptForLogicalInfo():
    bundle = {"name" : "", "hosts" : [], "bundle_location" : "", "version" : 1}
    
    print "\n" + textwrap.fill("A notary is a 'logical' entity that represents an " \
                                 "arbitrary number of physical hosts.  To create a " \
                                 "notary bundle, this script will prompt you for general " \
                                 "information about the logical notary entity, and then for " \
                                 "information about the physical notary hosts.", 78)


    print "\n\n" + textwrap.fill("First, please enter the name of the entity managing this notary. " \
                                 "For an individual, this would be an individual's " \
                                 "name (eg: John Smith). For an organization, this " \
                                 "would be the organization's name (eg: Acme).", 78) + "\n"

    bundle['name'] = loopingPrompt("Notary name: ")

    print "\n\n" + textwrap.fill("Next, please enter the complete URL for where this bundle will " \
                                 "be hosted (eg: https://thoughtcrime.org/thoughtcrime.notary).  It must " \
                                 "be an https URL, and the file must have a '.notary' " \
                                 "extension. This location will be periodically checked by clients for " \
                                 "updates to your notary configuration.", 78) + "\n"

    bundle['bundle_location'] = loopingPrompt("Bundle location: ")

    while (not bundle['bundle_location'].startswith("https://")) or (not bundle['bundle_location'].endswith(".notary")):
        print textwrap.fill("Sorry, the bundle location must be an HTTPS URL and have a '.notary' file extension.", 78)
        bundle['bundle_location'] = loopingPrompt("Bundle location: ")
    
    return bundle
开发者ID:hmco,项目名称:Convergence,代码行数:30,代码来源:convergence-bundle.py

示例6: _tooltip

 def _tooltip(self, widget, x, y, keyboard_mode, tooltip):
     """ Show current event in tooltip """
     # Silver Rain
     silver = Gtk.Label()
     silver.set_markup("<b>{0}</b>".format(_("Silver Rain")))
     # Icon
     img = Gtk.Image.new_from_pixbuf(self._event_icon)
     # Program
     title = Gtk.Label()
     str = textwrap.fill(self._event_title, 21)
     title.set_markup("<b>" + str + "</b>")
     title.set_alignment(0, 0.5)
     host = Gtk.Label()
     str = textwrap.fill(self._event_host, 21)
     host.set_text(str)
     host.set_alignment(0, 0.5)
     time = Gtk.Label()
     time.set_text(self._event_time)
     time.set_alignment(0, 0.5)
     # Pack
     box = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=15)
     box.set_border_width(10)
     grid = Gtk.Grid()
     grid.set_column_spacing(20)
     grid.attach(img,    0, 0, 1, 3)
     grid.attach(title,  1, 0, 1, 1)
     grid.attach(host,   1, 1, 1, 1)
     grid.attach(time,   1, 2, 1, 1)
     box.pack_start(silver, False, False, 0)
     box.pack_start(grid, False, False, 0)
     # Show
     box.show_all()
     tooltip.set_custom(box)
     return True
开发者ID:petrskovoroda,项目名称:silver-rain,代码行数:34,代码来源:statusicon.py

示例7: get_spell_info

def get_spell_info(spell, width=70):
    spellDict = lib.registry.lookup_by_name(spell=spell)
    spellObj = spellDict['spell']
    if not spellDict['spell']:
        raise RuntimeError()

    yield '  * Name: %s' % spellObj.__name__
    yield textwrap.fill(
        '  * Description: %s' % spellObj.__doc__,
        width=width, subsequent_indent=' ' * 4
    )
    if spellObj.config:
        yield '  * Required configs:'
        for config in spellObj.config:
            yield '      - %s' % config
    else:
        yield '  * Required configs: None'

    if spellDict['test']:
        queries = spellDict['test'].collectQueries()
        yield '  * Example usage:'
        for query, result in queries.iteritems():
            yield textwrap.fill(
                '      >>> %s' % query,
                width=width, subsequent_indent=' ' * 10
            )
            yield textwrap.fill(
                '      ... %s' % result,
                width=width, subsequent_indent=' ' * 10
            )
开发者ID:dvrasp,项目名称:TheTroz,代码行数:30,代码来源:troz.py

示例8: print_dict

def print_dict(d, dict_property="Property", wrap=0):
    pt = prettytable.PrettyTable([dict_property, 'Value'],
                                 caching=False, print_empty=False)
    pt.align = 'l'
    for k, v in sorted(six.iteritems(d)):
        # convert dict to str to check length
        if isinstance(v, dict):
            v = str(v)
        if isinstance(v, six.string_types):
            v = strutils.safe_encode(v)
        # if value has a newline, add in multiple rows
        # e.g. fault with stacktrace
        if v and isinstance(v, six.string_types) and r'\n' in v:
            lines = v.strip().split(r'\n')
            col1 = k
            for line in lines:
                if wrap > 0:
                    line = textwrap.fill(str(line), wrap)
                pt.add_row([col1, line])
                col1 = ''
        else:
            if wrap > 0:
                v = textwrap.fill(str(v), wrap)
            pt.add_row([k, v])
    print(pt.get_string())
开发者ID:wputra,项目名称:MOS-centos,代码行数:25,代码来源:utils.py

示例9: look

	def look(self):
		print "-" * 42
		print self.name.center(42, " ")
		print "-" * 42
		print ""
		print textwrap.fill(self.ldesc, 42)
		print ""
开发者ID:alexiecakes,项目名称:the-kingdom-of-nymakhia,代码行数:7,代码来源:nymakhia.py

示例10: main_parser

def main_parser():
    parser = argparse.ArgumentParser(
        usage=argparse.SUPPRESS,
        description=textwrap.fill(textwrap.dedent("""\
                    OpenERP Command provides a set of command-line tools around
                    the OpenERP framework: openobject-server. All the tools are
                    sub-commands of a single oe executable.""")),
        epilog="""Use <command> --help to get information about the command.""",
        formatter_class=argparse.RawDescriptionHelpFormatter,
    )
    description = []
    for x in command_list_server:
        description.append(x.__name__[len(__package__)+1:])
        if x.__doc__:
            description.extend([
                ":\n",
                textwrap.fill(str(x.__doc__).strip(),
                              subsequent_indent='  ',
                              initial_indent='  '),
            ])
        description.append("\n\n")
    subparsers = parser.add_subparsers(
        title="Available commands",
        help=argparse.SUPPRESS,
        description="".join(description[:-1]),
    )
    # Server-side commands.
    for x in command_list_server:
        x.add_parser(subparsers)
    # Client-side commands. TODO one per .py file.
    for x in command_list_client:
        x(subparsers)
    return parser
开发者ID:Giyyan,项目名称:upink_server,代码行数:33,代码来源:__init__.py

示例11: toolTip

    def toolTip(self, column):
        """Return tooltip for column."""
        try:
            ds = self.doc.data[self.data[0]]
        except KeyError:
            return None

        c = self.cols[column]
        if c == "name":
            text = ds.description()
            if text is None:
                text = ''

            if ds.tags:
                text += '\n\n' + _('Tags: %s') % (' '.join(sorted(ds.tags)))

            return textwrap.fill(text, 40)
        elif c == "size" or (c == 'type' and 'size' not in self.cols):
            text = ds.userPreview()
            # add preview of dataset if possible
            pix = self.getPreviewPixmap(ds)
            if pix:
                text = text.replace("\n", "<br>")
                text = "<html>%s<br>%s</html>" % (text, utils.pixmapAsHtml(pix))
            return text
        elif c == "linkfile" or c == "type":
            return textwrap.fill(ds.linkedInformation(), 40)
        return None
开发者ID:eegroopm,项目名称:veusz,代码行数:28,代码来源:datasetbrowser.py

示例12: _extensionIndexCommitMessage

  def _extensionIndexCommitMessage(self, name, description, update, wrap=True):
    args = description.__dict__
    args["name"] = name

    if update:
      template = textwrap.dedent("""\
        ENH: Update %(name)s extension

        This updates the %(name)s extension to %(scmrevision)s.
        """)
      if wrap:
        paragraphs = (template % args).split("\n")
        return "\n".join([textwrap.fill(p, width=76) for p in paragraphs])
      else:
        return template % args

    else:
      template = textwrap.dedent("""\
        ENH: Add %(name)s extension

        Description:
        %(description)s

        Contributors:
        %(contributors)s
        """)

      if wrap:
        for key in args:
          args[key] = textwrap.fill(args[key], width=72)

      return template % args
开发者ID:LucasGandel,项目名称:Slicer,代码行数:32,代码来源:ExtensionWizard.py

示例13: main

def main():
    if len(args) < 1:
	sys.stderr.write("No rating string provided! Exiting...\n")
	sys.exit(1)
    rating_string = ' '.join(args)
    print "Input composite rating string: ", rating_string
    
    prepped_string = prep_composite_rating(rating_string)
    print "Prepped composite rating string:", prepped_string
    rating_tables = get_tables(prepped_string)
   
    where_clause = prep_composite_rating(options.where_clause)
    print "Where clause:", where_clause
    where_tables = get_tables(where_clause)
  
    tables = sorted(list(set(where_tables+rating_tables)))
    print "MySQL DB tables to use:", ', '.join(tables)

    query = build_query(prepped_string, where=where_clause)
    print "MySQL query to compute composite rating:"
    print textwrap.fill(query, width=72, initial_indent='\t', subsequent_indent='\t')

    produce_report(prepped_string, numbins=options.numbins, \
			where=where_clause, norm=options.norm, \
			log=options.log)
开发者ID:plazar,项目名称:ratings,代码行数:25,代码来源:composite_rating_report.py

示例14: show_info

 def show_info(self):
     self.info['Path'] = os.path.join('modules', self._modulename) + '.py'
     print('')
     # meta info
     for item in ['Name', 'Path', 'Author', 'Version']:
         if item in self.info:
             print('%s: %s' % (item.rjust(10), self.info[item]))
     #dirs = self._modulename.split('/')
     #if dirs[0] == 'recon':
     #    print('%s: %s => %s' % ('Transform'.rjust(10), dirs[1].upper(), dirs[2].upper()))
     print('')
     # description
     if 'Description' in self.info:
         print('Description:')
         print('%s%s' % (self.spacer, textwrap.fill(self.info['Description'], 100, subsequent_indent=self.spacer)))
         print('')
     # options
     print('Options:', end='')
     self.show_options()
     # sources
     if hasattr(self, '_default_source'):
         print('Source Options:')
         print('%s%s%s' % (self.spacer, 'default'.ljust(15), self._default_source))
         print('%s%sstring representing a single input' % (self.spacer, '<string>'.ljust(15)))
         print('%s%spath to a file containing a list of inputs' % (self.spacer, '<path>'.ljust(15)))
         print('%s%sdatabase query returning one column of inputs' % (self.spacer, 'query <sql>'.ljust(15)))
         print('')
     # comments
     if 'Comments' in self.info and self.info['Comments']:
         print('Comments:')
         for comment in self.info['Comments']:
             print('%s%s' % (self.spacer, textwrap.fill('* %s' % (comment), 100, subsequent_indent=self.spacer)))
         print('')
开发者ID:13108989848,项目名称:pydra,代码行数:33,代码来源:module.py

示例15: hasher

def hasher(filename, blocksize=-1):
    # Hash the file, returning MD5 and SHA1 in an optimal manner. Most of this code is error handling.
    hashmd5 = hashlib.md5()
    hashsha1 = hashlib.sha1()
    try:
        with open(filename, "rb") as f:
            for block in iter(lambda: f.read(blocksize), ""):
                hashmd5.update(block)
                hashsha1.update(block)

    except IOError:
        err = "Error: Unable to read the file \"%s\". Make sure you have permission to read this file.  You may have " \
                "to disable or uninstall anti-virus to stop it from denying access to the file.  Correct this " \
                "problem and try again." % filename
        sys.stderr.write(textwrap.fill(err, width=term_width()) + "\n")
        sys.exit(-1)

    except MemoryError:
        # OOM, revert to the smaller blocksize for this file
        #print "DEBUG: Reducing block size for the file %s"%filename
        if blocksize != -1:
            # Blocksize is already small - bail
            err = "Error: Unable to read the file \"%s\" into memory. This could be caused by anti-virus, or by " \
                    "other system instability issues. Kill some running processes before trying again." % filename
            sys.stderr.write(textwrap.fill(err, width=term_width()) + "\n")
            sys.exit(-1)

        # We can't recover if this fails, so no try/except block.
        with open(filename, "rb") as f:
            for block in iter(lambda: f.read(SMALLBLOCK), ""):
                hashmd5.update(block)
                hashsha1.update(block)

    return (hashmd5.hexdigest(), hashsha1.hexdigest())
开发者ID:philhagen,项目名称:bitfit,代码行数:34,代码来源:bitfit.py


注:本文中的textwrap.fill函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。