我们从Python开源项目中,提取了以下47个代码示例,用于说明如何使用textwrap.fill()。
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)
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
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)
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 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 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 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 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 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
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
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)
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)
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))
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+' ')
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
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
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)