Python textwrap.shorten() Examples

The following are 30 code examples of textwrap.shorten(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module textwrap , or try the search function .
Example #1
Source File: up2lower.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir = args.files, args.out
    keep_src, recursive = args.keep, args.recursive
    # if the out_dir is None and --keep is setted, process as an error
    if keep_src and out_dir is None:
        err_message = 'Error! Blank output directory is conflict with --keep.'
        print(err_message, file=sys.stderr)
        return 1
    # start process
    if out_dir is not None:
        os.makedirs(out_dir, exist_ok=True)
    # collect input globstrs into a glob list
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    count = 0
    for src_file in itertools.chain(*globs):
        up2lower(src_file, out_dir, keep_src)
        count += 1

    print('{} files have been processed.'.format(count))

    return 0 
Example #2
Source File: common.py    From pypath with GNU General Public License v3.0 6 votes vote down vote up
def wrap_truncate(text, width = None, maxlen = None):
    
    if isinstance(text, list_like):
        
        text = ', '.join(text)
    
    if not isinstance(text, basestring):
        
        text = str(text)
    
    if maxlen:
        
        text = textwrap.shorten(text, width = maxlen)
    
    if width:
        
        text = textwrap.wrap(text, width = width)
    
    return os.linesep.join(text) if isinstance(text, list_like) else text 
Example #3
Source File: test_infractions.py    From bot with MIT License 6 votes vote down vote up
def test_apply_ban_reason_truncation(self, post_infraction_mock, get_active_mock):
        """Should truncate reason for `ctx.guild.ban`."""
        get_active_mock.return_value = None
        post_infraction_mock.return_value = {"foo": "bar"}

        self.cog.apply_infraction = AsyncMock()
        self.bot.get_cog.return_value = AsyncMock()
        self.cog.mod_log.ignore = Mock()
        self.ctx.guild.ban = Mock()

        await self.cog.apply_ban(self.ctx, self.target, "foo bar" * 3000)
        self.ctx.guild.ban.assert_called_once_with(
            self.target,
            reason=textwrap.shorten("foo bar" * 3000, 512, placeholder="..."),
            delete_message_days=0
        )
        self.cog.apply_infraction.assert_awaited_once_with(
            self.ctx, {"foo": "bar"}, self.target, self.ctx.guild.ban.return_value
        ) 
Example #4
Source File: unfurl_message.py    From gitlab-unfurly with MIT License 6 votes vote down vote up
def get_note_merge_requests_info(session, path_info):
    api_path = f"/api/v4/projects/{path_info.quoted_id}/merge_requests/{path_info.identifier}/notes/{path_info.note}"
    data = get_data_from_api(session, api_path)
    mr_data = get_merge_request_data(session, path_info)

    try:
        mr_title = mr_data["title"].strip()
        mr_state = mr_data["state"]
        body = data["body"]
    except IndexError as e:
        log.exception(f"Err in data from GL: {e}")
        raise
    return {
        "author_name": format_user(data["author"]),
        "author_link": data["author"]["web_url"],
        "author_icon": data["author"]["avatar_url"],
        "title": f"Comment on merge request: {mr_title}",
        "text": textwrap.shorten(body.strip(), width=300, placeholder="…"),
        "color": MR_STATE_COLORS[mr_state],
        "ts": arrow.get(data["created_at"]).timestamp,
        "footer": "Merge Request Note",
    } 
Example #5
Source File: rnx2crnx.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir = args.files, args.out
    keep_src, recursive = args.keep, args.recursive
    # create output directory
    os.makedirs(out_dir, exist_ok=True)
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    # make input args for rnx2crx function
    conv_args = ((src, out_dir, keep_src) for src in itertools.chain(*globs))
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    if not keep_src:
        print('Delete source files when complete')
    # start parallel task, get a file name list of convert failed.
    failed = parallel_run(rnx2crx, conv_args)
    if failed:
        print('\nConvert failed filename: {}'.format(', '.join(failed)))
    else:
        print('\nAll convert tasks are finished!') 
Example #6
Source File: qualitycheck.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_fmt, recursive = args.files, args.out, args.recursive
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    src_files = [src for src in itertools.chain(*globs)]
    # make input args for teqc function
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    # if output format is table, print a table header first
    if out_fmt == 'table' or out_fmt == 't':
        header = ('file', 'date', 'start', 'end', 'hours', 'percent',
                  'SN1', 'SN2', 'MP1', 'MP2', 'CSR')
        style = ('\n{0: ^14s} {1: ^12s} {2: ^14s} {3: ^14s} {4: >6s}  {5: >7s}'
                 '{6: >6s}  {7: >6s}  {8: >6s}  {9: >5s}  {10: >5s}')
        print(style.format(*header))
    # start parallel processing
    failed = parallel_teqc(src_files, args.nav, out_fmt)
    if failed:
        print('\nQuality check failed files: {}'.format(', '.join(failed)))

    return 0 
Example #7
Source File: renamesite.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir, sitemap = args.files, args.out, yaml.load(args.cfg)
    keep_src, recursive = args.keep, args.recursive
    # make output directory if out_dir is set
    if out_dir is not None:
        os.makedirs(out_dir, exist_ok=True)
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    # start process
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    if not keep_src:
        print('Delete source files when complete')
    missing = set()
    for src_file in itertools.chain(*globs):
        res = rename_site(src_file, out_dir, sitemap, keep_src)
        # if return is not None, means site not found in sitemap
        if res is not None:
            missing.add(res)

    if missing:
        print('Sites not found in sitemap: {}'.format(', '.join(missing)))

    return 0 
Example #8
Source File: tui.py    From awesome-finder with MIT License 6 votes vote down vote up
def display(self):
        """Display the found awesome content on result window"""
        self.result_window.erase()
        for idx, val in enumerate(self.matched_blocks[self.top:self.top + self.max_lines]):
            if val['type'] == 'category':
                # Highlight the current cursor line
                if idx == self.current:
                    self.result_window.addstr(idx, 0, shorten(val['line'], self.width, placeholder='...'),
                                              curses.color_pair(2))
                else:
                    self.result_window.addstr(idx, 0, shorten(val['line'], self.width, placeholder='...'),
                                              curses.color_pair(1))
            elif val['type'] == 'awesome':
                # Highlight the current cursor line
                if idx == self.current:
                    self.result_window.addstr(idx, 2, shorten(val['line'], self.width - 3, placeholder='...'),
                                              curses.color_pair(2))
                else:
                    self.result_window.addstr(idx, 2, shorten(val['line'], self.width - 3, placeholder='...'))
        self.result_window.refresh() 
Example #9
Source File: helper.py    From twtxt with MIT License 6 votes vote down vote up
def style_tweet(tweet, porcelain=False):
    conf = click.get_current_context().obj["conf"]
    limit = conf.character_limit

    if porcelain:
        return "{nick}\t{url}\t{tweet}".format(
            nick=tweet.source.nick,
            url=tweet.source.url,
            tweet=str(tweet))
    else:
        if sys.stdout.isatty() and not tweet.text.isprintable():
            return None
        styled_text = format_mentions(tweet.text)
        len_styling = len(styled_text) - len(click.unstyle(styled_text))
        final_text = textwrap.shorten(styled_text, limit + len_styling) if limit else styled_text
        timestamp = tweet.absolute_datetime if conf.use_abs_time else tweet.relative_datetime
        return "➤ {nick} ({time}):\n{tweet}".format(
            nick=click.style(tweet.source.nick, bold=True),
            tweet=final_text,
            time=click.style(timestamp, dim=True)) 
Example #10
Source File: orderfile.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir = args.files, args.out
    keep_src, recursive = args.keep, args.recursive
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    # start process
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    if not keep_src:
        print('Delete source files when complete')
    for src_file in itertools.chain(*globs):
        dst_dir = os.path.join(out_dir, which_dir(src_file))
        os.makedirs(dst_dir, exist_ok=True)
        print('{} => {}'.format(src_file, dst_dir))
        if keep_src:
            shutil.copy2(src_file, dst_dir)
        else:
            shutil.move(src_file, dst_dir)

    return 0 
Example #11
Source File: low2upper.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir = args.files, args.out
    keep_src, recursive = args.keep, args.recursive
    # if the out_dir is None and --keep is setted, process as an error
    if keep_src and out_dir is None:
        err_message = 'Error! Blank output directory is conflict with --keep.'
        print(err_message, file=sys.stderr)
        return 1
    # start process
    if out_dir is not None:
        os.makedirs(out_dir, exist_ok=True)
    # collect input globstrs into a glob list
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    count = 0
    for src_file in itertools.chain(*globs):
        low2upper(src_file, out_dir, keep_src)
        count += 1

    print('{} files have been processed.'.format(count))

    return 0 
Example #12
Source File: unificate.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function"""
    args = init_args()
    globstrs, out_dir, infos = args.files, args.out, yaml.load(args.cfg)
    keep_src, recursive = args.keep, args.recursive
    # create output directory
    os.makedirs(out_dir, exist_ok=True)
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    files = itertools.chain(*globs)
    # make input args for teqc function
    teqc_args = ((src, make_args(src, infos), out_dir, keep_src) for src in files)
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    if not keep_src:
        print('Delete source files when complete')
    # start parallel task, get a filename list of unificate failed.
    failed = parallel_run(teqc, teqc_args)
    if failed:
        print('\nUnificate failed filename: {}'.format(', '.join(failed)))
    else:
        print('\nAll unificate tasks are finished!')

    return 0 
Example #13
Source File: crnx2rnx.py    From pinot with GNU General Public License v2.0 6 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir = args.files, args.out
    keep_src, recursive = args.keep, args.recursive
    # create output directory
    os.makedirs(out_dir, exist_ok=True)
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    # make input args for crx2rnx function
    conv_args = ((src, out_dir, keep_src) for src in itertools.chain(*globs))
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    if not keep_src:
        print('Delete source files when complete')
    # start parallel task, get a file name list of convert failed.
    failed = parallel_run(crx2rnx, conv_args)
    if failed:
        print('\nConvert failed filename: {}'.format(', '.join(failed)))
    else:
        print('\nAll convert tasks are finished!') 
Example #14
Source File: player.py    From storybro with MIT License 6 votes vote down vote up
def format_block_for_list(self, block, index, index_width):
        if block.attrs.get('type') == 'input':
            icon = self.settings.icon_for_input
        else:
            icon = self.settings.icon_for_output

        if block.attrs.get('pinned'):
            pin = self.settings.icon_for_pins
        else:
            pin = "  "

        index_label = str(index).rjust(index_width)

        text = block.text

        if self.settings.fill_width:
            text = textwrap.shorten(text, self.settings.fill_width, placeholder="")

        return f"{icon}{pin} {index_label}: {text}" 
Example #15
Source File: subnet.py    From pinot with GNU General Public License v2.0 5 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_dir, config = args.files, args.out, yaml.load(args.cfg)
    keep_src, recursive = args.keep, args.recursive
    # convert sites list into set
    nets = {net: set(sites) for net, sites in config.items()}
    net_dirs = {net: os.path.join(out_dir, net) for net in nets}
    # create folder for every subnet
    for subdir in net_dirs.values():
        os.makedirs(subdir, exist_ok=True)
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    # start process
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    if not keep_src:
        print('Delete source files when complete')
    missing = set()
    for src_file in itertools.chain(*globs):
        belong = which_nets(src_file, nets)
        # if couldn't found a site in any subnets, log it
        if not belong:
            missing.add(os.path.basename(src_file)[0:4].lower())
            continue
        # get all destination directories and copy/move in
        dst_dirs = [net_dirs[net] for net in belong]
        order_file(src_file, dst_dirs, keep_src)

    if missing:
        message = 'Sites not belong to any networks: {}'
        print(message.format(', '.join(missing)))

    return 0 
Example #16
Source File: admin.py    From coldfront with GNU General Public License v3.0 5 votes vote down vote up
def project(self, obj):
        return textwrap.shorten(obj.allocation.project.title, width=50) 
Example #17
Source File: metacheck.py    From pinot with GNU General Public License v2.0 5 votes vote down vote up
def main():
    """Main function."""
    args = init_args()
    globstrs, out_fmt, sitesinfo = args.files, args.out, yaml.load(args.cfg)
    threshold, recursive = args.thd, args.recursive
    # collect input globstrs into a glob list
    globs = [glob.iglob(globstr, recursive=recursive) for globstr in globstrs]
    # start process
    print('Start processing: {}'.format(shorten(', '.join(globstrs), 62)))
    # if output format is table, print a table header first
    if out_fmt == 'table' or out_fmt == 't':
        header = 'file', 'type', 'in cfgfile', 'in obsfile'
        print('\n{: <20s} {: <10s} {: <44s} {: <44s}'.format(*header))
    # a set named missing collects site not found in reference file
    missing = set()
    for src_file in itertools.chain(*globs):
        filename = os.path.basename(src_file)
        site = filename[0:4].lower()
        # if site not in sitesinfo, add this site info missing
        if site not in sitesinfo:
            missing.add(site)
            continue
        fileinfo = get_meta(open(src_file))
        difference = compare_info(fileinfo, sitesinfo[site], threshold)
        if difference:
            show_difference(src_file, difference, out_fmt)

    if missing:
        message = '\nSites not found in configuration file: {}'
        print(message.format(', '.join(sorted(list(missing)))))

    return 0 
Example #18
Source File: tables.py    From hypha with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def render_title(record):
    try:
        title = record.title
    except AttributeError:
        title = record.submission.title
    return textwrap.shorten(title, width=30, placeholder="...") 
Example #19
Source File: test_textwrap.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def test_width_too_small_for_placeholder(self):
        shorten("x" * 20, width=8, placeholder="(......)")
        with self.assertRaises(ValueError):
            shorten("x" * 20, width=8, placeholder="(.......)") 
Example #20
Source File: test_textwrap.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def check_shorten(self, text, width, expect, **kwargs):
        result = shorten(text, width, **kwargs)
        self.check(result, expect) 
Example #21
Source File: unfurl_message.py    From gitlab-unfurly with MIT License 5 votes vote down vote up
def prepare_description(description, *, width=100):
    description = strip_html_tags(description)
    description = description.strip()
    return textwrap.shorten(description, width, placeholder="…") 
Example #22
Source File: test_textwrap.py    From android_universal with MIT License 5 votes vote down vote up
def check_shorten(self, text, width, expect, **kwargs):
        result = shorten(text, width, **kwargs)
        self.check(result, expect) 
Example #23
Source File: test_textwrap.py    From android_universal with MIT License 5 votes vote down vote up
def test_width_too_small_for_placeholder(self):
        shorten("x" * 20, width=8, placeholder="(......)")
        with self.assertRaises(ValueError):
            shorten("x" * 20, width=8, placeholder="(.......)") 
Example #24
Source File: exception_handler.py    From renku-python with Apache License 2.0 5 votes vote down vote up
def _format_issue_title(self):
        """Return formatted title."""
        return textwrap.shorten(
            'cli: renku ' + ' '.join(sys.argv[1:]),
            width=50,
        ) 
Example #25
Source File: test_infractions.py    From bot with MIT License 5 votes vote down vote up
def test_apply_kick_reason_truncation(self, post_infraction_mock):
        """Should truncate reason for `Member.kick`."""
        post_infraction_mock.return_value = {"foo": "bar"}

        self.cog.apply_infraction = AsyncMock()
        self.cog.mod_log.ignore = Mock()
        self.target.kick = Mock()

        await self.cog.apply_kick(self.ctx, self.target, "foo bar" * 3000)
        self.target.kick.assert_called_once_with(reason=textwrap.shorten("foo bar" * 3000, 512, placeholder="..."))
        self.cog.apply_infraction.assert_awaited_once_with(
            self.ctx, {"foo": "bar"}, self.target, self.target.kick.return_value
        ) 
Example #26
Source File: utils.py    From bot with MIT License 5 votes vote down vote up
def notify_infraction(
    user: UserObject,
    infr_type: str,
    expires_at: t.Optional[str] = None,
    reason: t.Optional[str] = None,
    icon_url: str = Icons.token_removed
) -> bool:
    """DM a user about their new infraction and return True if the DM is successful."""
    log.trace(f"Sending {user} a DM about their {infr_type} infraction.")

    text = textwrap.dedent(f"""
        **Type:** {infr_type.capitalize()}
        **Expires:** {expires_at or "N/A"}
        **Reason:** {reason or "No reason provided."}
    """)

    embed = discord.Embed(
        description=textwrap.shorten(text, width=2048, placeholder="..."),
        colour=Colours.soft_red
    )

    embed.set_author(name="Infraction information", icon_url=icon_url, url=RULES_URL)
    embed.title = f"Please review our rules over at {RULES_URL}"
    embed.url = RULES_URL

    if infr_type in APPEALABLE_INFRACTIONS:
        embed.set_footer(
            text="To appeal this infraction, send an e-mail to appeals@pythondiscord.com"
        )

    return await send_private_embed(user, embed) 
Example #27
Source File: infractions.py    From bot with MIT License 5 votes vote down vote up
def apply_kick(self, ctx: Context, user: Member, reason: t.Optional[str], **kwargs) -> None:
        """Apply a kick infraction with kwargs passed to `post_infraction`."""
        infraction = await utils.post_infraction(ctx, user, "kick", reason, active=False, **kwargs)
        if infraction is None:
            return

        self.mod_log.ignore(Event.member_remove, user.id)

        if reason:
            reason = textwrap.shorten(reason, width=512, placeholder="...")

        action = user.kick(reason=reason)
        await self.apply_infraction(ctx, infraction, user, action) 
Example #28
Source File: errors.py    From stig with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, response):
        super().__init__('Invalid RPC response',
                         textwrap.shorten(response, 100, placeholder='...')) 
Example #29
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def check_shorten(self, text, width, expect, **kwargs):
        result = shorten(text, width, **kwargs)
        self.check(result, expect) 
Example #30
Source File: test_textwrap.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def test_width_too_small_for_placeholder(self):
        shorten("x" * 20, width=8, placeholder="(......)")
        with self.assertRaises(ValueError):
            shorten("x" * 20, width=8, placeholder="(.......)")