本文整理汇总了Python中textwrap.fill函数的典型用法代码示例。如果您正苦于以下问题:Python fill函数的具体用法?Python fill怎么用?Python fill使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了fill函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
示例16: print_options
def print_options(option_list):
import textwrap
from auxcodes import bcolors
# expected to be called if a config file is not specified. Print a
# list of options
option_list=sorted(option_list,key=lambda x:x[1])
width,height=_get_terminal_size_linux()
sections=sorted(set(x[0] for x in option_list))
klen=max([len(x[1]) for x in option_list])
tlen=max([len(typename(x[2])) for x in option_list])
fstring='%-'+str(klen)+'s = %-'+str(tlen)+'s (default %s)'
indent=' '*(klen+3)
for s in sections:
print bcolors.OKBLUE+'\n[%s]' % s+bcolors.ENDC
for o in option_list:
if len(o)==4:
(section, name, otype, default)=o
doc=None
elif len(o)==5:
(section, name, otype, default, doc)=o
else:
print 'Oops!',o
continue
if section==s:
print bcolors.BOLD+fstring % (name, typename(otype), str(default))+bcolors.ENDC
if doc is not None:
print textwrap.fill(doc,width-1,initial_indent=indent,subsequent_indent=indent)
开发者ID:mhardcastle,项目名称:ddf-pipeline,代码行数:28,代码来源:options.py
示例17: getHelpTopic
def getHelpTopic(self, topic, app):
import io
import textwrap
from piecrust.chefutil import print_help_item
with io.StringIO() as tplh:
extensions = app.plugin_loader.getCommandExtensions()
for e in extensions:
if e.command_name == 'prepare' and e.supports(app):
for n in e.getTemplateNames(app):
d = e.getTemplateDescription(app, n)
print_help_item(tplh, n, d)
help_list = tplh.getvalue()
help_txt = (
textwrap.fill(
"Running the 'prepare' command will let "
"PieCrust setup a page for you in the correct place, with "
"some hopefully useful default text.") +
"\n\n" +
textwrap.fill("The following templates are available:") +
"\n\n" +
help_list +
"\n" +
"You can add user-defined templates by creating pages in a "
"`scaffold/pages` sub-directory in your website.")
return help_txt
开发者ID:ludovicchabant,项目名称:PieCrust2,代码行数:27,代码来源:scaffolding.py
示例18: main
def main():
paths = sys.argv[1:] or ['.']
print 'Importing nltk...'
try:
import nltk
except ImportError:
print 'Unable to import nltk -- check your PYTHONPATH.'
sys.exit(-1)
print 'Finding definitions of deprecated funtions & classes in nltk...'
find_deprecated_defs(nltk.__path__[0])
print 'Looking for possible uses of deprecated funcs & classes...'
dep_names = print_deprecated_uses(paths)
if not dep_names:
print 'No deprecated funcs or classes found!'
else:
print "\n"+term.BOLD+"What you should use instead:"+term.NORMAL
for name in sorted(dep_names):
msgs = deprecated_funcs[name].union(
deprecated_classes[name]).union(
deprecated_methods[name])
for msg, prefix, suffix in msgs:
print textwrap.fill(term.RED+prefix+name+suffix+
term.NORMAL+': '+msg,
width=75, initial_indent=' '*2,
subsequent_indent=' '*6)
开发者ID:Joselin,项目名称:nltk,代码行数:29,代码来源:find_deprecated.py
示例19: demo
def demo(train_size=100, test_size=100, java_home=None, mallet_home=None):
from nltk.corpus import brown
import textwrap
# Define a very simple feature detector
def fd(sentence, index):
word = sentence[index]
return dict(word=word, suffix=word[-2:], len=len(word))
# Let nltk know where java & mallet are.
nltk.internals.config_java(java_home)
nltk.classify.mallet.config_mallet(mallet_home)
# Get the training & test corpus. We simplify the tagset a little:
# just the first 2 chars.
def strip(corpus): return [[(w, t[:2]) for (w,t) in sent]
for sent in corpus]
brown_train = strip(brown.tagged_sents(categories='news')[:train_size])
brown_test = strip(brown.tagged_sents(categories='editorial')[:test_size])
crf = MalletCRF.train(fd, brown_train, #'/tmp/crf-model',
transduction_type='VITERBI')
sample_output = crf.tag([w for (w,t) in brown_test[5]])
acc = nltk.tag.accuracy(crf, brown_test)
print '\nAccuracy: %.1f%%' % (acc*100)
print 'Sample output:'
print textwrap.fill(' '.join('%s/%s' % w for w in sample_output),
initial_indent=' ', subsequent_indent=' ')+'\n'
# Clean up
print 'Clean-up: deleting', crf.filename
os.remove(crf.filename)
return crf
开发者ID:0day1day,项目名称:golismero,代码行数:34,代码来源:crf.py
示例20: see
def see(ms):
clear_screen()
if LinkTopicHomeRaw[ms] == "":
update_data_home()
# Tach du lieu trang can xem vao mang
source_linebyline = convert_unicode_2_ascii(sourcetext(LinkTopicHomeRaw[ms])).splitlines()
print "\n\n\n"
print "===================================================="
print "===================================================="
print "========= Enter de xem tiep!! =========="
print "\n\n\n"
print textwrap.fill(" " + "[" + str(ms) + "]:" + TenTopicHome[ms])
print "\n"
for i in range(0, source_linebyline.__len__()):
if source_linebyline[i] != "":
print '\n'
# Wrap lai, xong in tung dong de can chinh le trai
for element in textwrap.wrap(source_linebyline[i], 75):
print " " + element
# Thay the do while
while True:
key = msvcrt.getch()
if ord(key) == 13:
break
continue
print "\n\n\n"
print "===================================================="
print "===================================================="
print "===================================================="
print "\n\n\n"
开发者ID:gitter-badger,项目名称:DNHconsole,代码行数:34,代码来源:DNHconsolelib.py
注:本文中的textwrap.fill函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论