def run_all(self):
"""Run all available testcases"""
tiers_to_run = []
msg = prettytable.PrettyTable(
header_style='upper', padding_width=5,
field_names=['tiers', 'order', 'CI Loop', 'description',
'testcases'])
for tier in self._tiers.get_tiers():
if (tier.get_tests() and
re.search(CONST.__getattribute__('CI_LOOP'),
tier.get_ci_loop()) is not None):
tiers_to_run.append(tier)
msg.add_row([tier.get_name(), tier.get_order(),
tier.get_ci_loop(),
textwrap.fill(tier.description, width=40),
textwrap.fill(' '.join([str(x.get_name(
)) for x in tier.get_tests()]), width=40)])
LOGGER.info("TESTS TO BE EXECUTED:\n\n%s\n", msg)
for tier in tiers_to_run:
self.run_tier(tier)
python类fill()的实例源码
def display_s3_bucket_validations_table(self, bucketlist):
'''
List the S3 buckets and the validation results in tabular format
'''
# Setup Table.
header = ["Bucket Name", "Profile",
"Naming Policy", "Tag Validation",
"Result"]
table = prettytable.PrettyTable(header)
for bucket in bucketlist:
name = bucket['Name']
profile = bucket['profile_name'][0]
naming_policy = bucket['validations']['nameresult']
tag_policy = textwrap.fill(bucket['validations']['tagresult'],
40)
result = bucket['validations']['result']
row = [name, profile, naming_policy, tag_policy, result]
table.add_row(row)
print table
def update(self):
# Update the labels.
problem = self.problems[self.problem]
self.category.set(problem.category)
self.question.set(textwrap.fill(problem.question, TEXT_WIDTH))
self.answer.set(textwrap.fill(problem.answer, TEXT_WIDTH // 2))
self.right.set(textwrap.fill(problem.right, TEXT_WIDTH // 2))
# Update the buttons.
if self.problem == 0:
self.back['state'] = DISABLED
else:
self.back['state'] = NORMAL
if self.problem + 1 == len(self.problems):
self.next['state'] = DISABLED
else:
self.next['state'] = NORMAL
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
Ataca_a_los_orcos_V1_0_0.py 文件源码
项目:Tutoriales_juegos_Python
作者: tidus747
项目源码
文件源码
阅读 32
收藏 0
点赞 0
评论 0
def Mostrar_mision(self):
print_bold("Ataca a los Orcos V1.0.0")
msg = ("La guerra entre los humanos y sus arqueros enemigos, los Orcos, estaba en el aire."
"Un enorme ejército de orcos se dirigía hacia los territos de los humanos. Destruían"
"prácticamente todo en su camino. Los grandes reyes de la raza humana, se unieron para"
" derrotar a su peor enemigo, era la gran batalla de su tiempo. Sir Gandorel, uno de los "
"valientes caballeros que guardan las llanuras meridionales, inició un largo viaje hacia el este"
", a través de un desconocido bosque espeso. Durante dos días y dos noches, se movió con cautela "
"a través del grueso bosque. En su camino, vio un pequeño asentamiento aislado. Cansado y con "
"la esperanza de reponer su stock de alimentos, decidió tomar un desvío. Cuando se acercó al pueblo,"
"vio cinco chozas. No había nadie alrededor. En ese instante, decidió entrar en un choza...")
print(textwrap.fill(msg, width = 72))
print_bold("Misión:")
print(" 1. Lucha contra el enemigo.")
print(" 2. Conquista cada una de las chozas hasta que estén bajo tu control")
print("-"*72)
Ataca_a_los_orcos_V1_0_0.py 文件源码
项目:Tutoriales_juegos_Python
作者: tidus747
项目源码
文件源码
阅读 25
收藏 0
点赞 0
评论 0
def Mostrar_mision(self):
print_bold("Ataca a los Orcos V1.0.0")
msg = ("La guerra entre los humanos y sus arqueros enemigos, los Orcos, estaba en el aire."
"Un enorme ejército de orcos se dirigía hacia los territos de los humanos. Destruían"
"prácticamente todo en su camino. Los grandes reyes de la raza humana, se unieron para"
" derrotar a su peor enemigo, era la gran batalla de su tiempo. Sir Gandorel, uno de los "
"valientes caballeros que guardan las llanuras meridionales, inició un largo viaje hacia el este"
", a través de un desconocido bosque espeso. Durante dos días y dos noches, se movió con cautela "
"a través del grueso bosque. En su camino, vio un pequeño asentamiento aislado. Cansado y con "
"la esperanza de reponer su stock de alimentos, decidió tomar un desvío. Cuando se acercó al pueblo,"
"vio cinco chozas. No había nadie alrededor. En ese instante, decidió entrar en un choza...")
print(textwrap.fill(msg, width = 72))
print_bold("Misión:")
print(" 1. Lucha contra el enemigo.")
print(" 2. Conquista cada una de las chozas hasta que estén bajo tu control")
print("-"*72)
Ataca_a_los_orcos_V0.0.5.py 文件源码
项目:Tutoriales_juegos_Python
作者: tidus747
项目源码
文件源码
阅读 26
收藏 0
点赞 0
评论 0
def mostrar_mision():
print("\033[1m"+ "Ataca a los Orcos V0.0.5" + "\033[0m")
msg = ("La guerra entre los humanos y sus arqueros enemigos, los Orcos, estaba en el aire."
"Un enorme ejército de orcos se dirigía hacia los territos de los humanos. Destruían"
"prácticamente todo en su camino. Los grandes reyes de la raza humana, se unieron para"
" derrotar a su peor enemigo, era la gran batalla de su tiempo. Sir Gandorel, uno de los "
"valientes caballeros que guardan las llanuras meridionales, inició un largo viaje hacia el este"
", a través de un desconocido bosque espeso. Durante dos días y dos noches, se movió con cautela "
"a través del grueso bosque. En su camino, vio un pequeño asentamiento aislado. Cansado y con "
"la esperanza de reponer su stock de alimentos, decidió tomar un desvío. Cuando se acercó al pueblo,"
"vio cinco chozas. No había nadie alrededor. En ese instante, decidió entrar en un choza...")
print(textwrap.fill(msg, width = 72))
print("\033[1m"+"Misión:"+"\033[0m")
print("Elige una choza donde poder descansar...")
print("\033[1m"+"NOTA:"+"\033[0m")
print("¡Cuidado! Hay enemigos rondando la zona")
print_linea_punteada()
def do_welcome():
title = """
_____ _ _
/ ____| | | | |
| | __ ___ _ __ _ __ ___| |_| |_ ____
| | |_ |/ _ \ '_ \| '_ \ / _ \ __| __/ _ |
| |__| | __/ |_) | |_) | __/ |_| || (_) |
\_____|\___| .__/| .__/ \___|\__|\__\___/
| | | |
|_| |_| The Cloud Maestro
"""
license = """THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE."""
license = '%s\n%s\n%s' % ('*' * 70, textwrap.fill(license, 70), '*' * 70,)
usage = """ """
print(title)
print(license)
print(usage)
def say(msg):
"""Print a message.
Unlike print(), this deals with de-denting and wrapping of text to fit
within the width of the terminal.
Paragraphs separated by blank lines in the input will be wrapped
separately.
"""
msg = str(msg)
msg = re.sub(r'^[ \t]*(.*?)[ \t]*$', r'\1', msg, flags=re.M)
width = get_terminal_size()[0]
paragraphs = re.split(r'\n(?:[ \t]*\n)', msg)
formatted = (textwrap.fill(p.strip(), width=width) for p in paragraphs)
print('\n\n'.join(formatted))
def _wrap_lines(msg):
"""Format lines nicely to 80 chars.
:param str msg: Original message
:returns: Formatted message respecting newlines in message
:rtype: str
"""
lines = msg.splitlines()
fixed_l = []
for line in lines:
fixed_l.append(textwrap.fill(
line,
80,
break_long_words=False,
break_on_hyphens=False))
return os.linesep.join(fixed_l)
def get_snippet_text(self, doc):
text = []
desc = CLI.tty_ify(doc['short_description'])
text.append("- name: %s" % (desc))
text.append(" action: %s" % (doc['module']))
pad = 31
subdent = " " * pad
limit = display.columns - pad
for o in sorted(doc['options'].keys()):
opt = doc['options'][o]
desc = CLI.tty_ify(" ".join(opt['description']))
required = opt.get('required', False)
if not isinstance(required, bool):
raise("Incorrect value for 'Required', a boolean is needed.: %s" % required)
if required:
s = o + "="
else:
s = o
text.append(" %-20s # %s" % (s, textwrap.fill(desc, limit, subsequent_indent=subdent)))
text.append('')
return "\n".join(text)
def _build_numpydoc(self):
numpydoc = []
numpydoc.append(textwrap.fill(self.name, width=75))
numpydoc.append(textwrap.fill(self.description, width=75))
sig = self.signature
params = collections.OrderedDict()
params.update(sig.inputs)
params.update(sig.parameters)
parameters = self._build_section("Parameters", params)
returns = self._build_section("Returns", sig.outputs)
for section in (parameters, returns):
if section:
numpydoc.append(section)
return '\n\n'.join(numpydoc) + '\n'
def _build_section(self, header, iterable):
section = []
if iterable:
section.append(header)
section.append('-'*len(header))
for key, value in iterable.items():
variable_line = (
"{item} : {type}".format(item=key, type=value.qiime_type))
if value.has_default():
variable_line += ", optional"
section.append(variable_line)
if value.has_description():
section.append(textwrap.indent(textwrap.fill(
str(value.description), width=71), ' '))
return '\n'.join(section).strip()
def wrap_paragraphs(text, ncols=80):
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
Returns
-------
list of complete paragraphs, wrapped to fill `ncols` columns.
"""
paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
text = dedent(text).strip()
paragraphs = paragraph_re.split(text)[::2] # every other entry is space
out_ps = []
indent_re = re.compile(r'\n\s+', re.MULTILINE)
for p in paragraphs:
# presume indentation that survives dedent is meaningful formatting,
# so don't fill unless text is flush.
if indent_re.search(p) is None:
# wrap paragraph
p = textwrap.fill(p, ncols)
out_ps.append(p)
return out_ps
def wrap_paragraphs(text, ncols=80):
"""Wrap multiple paragraphs to fit a specified width.
This is equivalent to textwrap.wrap, but with support for multiple
paragraphs, as separated by empty lines.
Returns
-------
list of complete paragraphs, wrapped to fill `ncols` columns.
"""
paragraph_re = re.compile(r'\n(\s*\n)+', re.MULTILINE)
text = dedent(text).strip()
paragraphs = paragraph_re.split(text)[::2] # every other entry is space
out_ps = []
indent_re = re.compile(r'\n\s+', re.MULTILINE)
for p in paragraphs:
# presume indentation that survives dedent is meaningful formatting,
# so don't fill unless text is flush.
if indent_re.search(p) is None:
# wrap paragraph
p = textwrap.fill(p, ncols)
out_ps.append(p)
return out_ps
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_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!
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')
def _wrap_lines(msg):
"""Format lines nicely to 80 chars.
:param str msg: Original message
:returns: Formatted message respecting newlines in message
:rtype: str
"""
lines = msg.splitlines()
fixed_l = []
for line in lines:
fixed_l.append(textwrap.fill(
line,
80,
break_long_words=False,
break_on_hyphens=False))
return os.linesep.join(fixed_l)
def input(self, message, **unused_kwargs):
# pylint: disable=no-self-use
"""Accept input from the user.
:param str message: message to display to the user
:param dict _kwargs: absorbs default / cli_args
:returns: tuple of (`code`, `input`) where
`code` - str display exit code
`input` - str of the user's input
:rtype: tuple
"""
ans = raw_input(
textwrap.fill(
"%s (Enter 'c' to cancel): " % message,
80,
break_long_words=False,
break_on_hyphens=False))
if ans == "c" or ans == "C":
return CANCEL, "-1"
else:
return OK, ans
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
def clear_targets(force = False):
if not force:
from os import _exit
import textwrap
warning = """
clear-targets will forcibly unmount and unconfigure all Lustre targets
on EVERY node in this HA domain. This is an irreversible and
potentially very destructive operation. Data loss may occur. Please
do not use it unless you fully understand the consequences! If you
are sure that this command does what you intend to do, then you must
supply the --force flag to avoid seeing this message.
"""
console_log.warn(textwrap.fill(textwrap.dedent(warning)))
_exit(1)
for resource, attrs in _query_ha_targets().items():
console_log.info("Stopping %s" % resource)
stop_target(attrs['ha_label'])
console_log.info("Unconfiguring %s" % resource)
unconfigure_target_ha(True, attrs['ha_label'], attrs['uuid'])
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+' ')
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+' ')
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)
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
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
def test_generator_expression(self):
self.assert_ok("""\
x = "-".join(str(z) for z in range(5))
assert x == "0-1-2-3-4"
""")
# From test_regr.py
# This failed a different way than the previous join when genexps were
# broken:
self.assert_ok("""\
from textwrap import fill
x = set(['test_str'])
width = 70
indent = 4
blanks = ' ' * indent
res = fill(' '.join(str(elt) for elt in sorted(x)), width,
initial_indent=blanks, subsequent_indent=blanks)
print(res)
""")
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!
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))