python类edit()的实例源码

inqurires.py 文件源码 项目:Harbor-CLI 作者: srishanbhattarai 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def getchangelog():
    '''
    Opens up EDITOR, and allows user to enter changelog.
    Splits by the boilerplate text and returns user input
    '''
    branch = git.branch() or '<unavailable>'
    user = git.username() or '<unavailable>'

    data = click.edit(
        text=RELEASE_LOG_TEXT.format(branch, user),
        require_save=True
    )
    try:
        serialized = data.split(RELEASE_LOG_TEXT.format(branch, user))

        return serialized[0]
    except Exception:  # pylint: disable=broad-except
        return ''
cli.py 文件源码 项目:pipenv 作者: pypa 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def run_open(module, three=None, python=None):

    # Ensure that virtualenv is available.
    ensure_project(three=three, python=python, validate=False)

    c = delegator.run('{0} -c "import {1}; print({1}.__file__);"'.format(which('python'), module))

    try:
        assert c.return_code == 0
    except AssertionError:
        click.echo(crayons.red('Module not found!'))
        sys.exit(1)

    if '__init__.py' in c.out:
        p = os.path.dirname(c.out.strip().rstrip('cdo'))
    else:
        p = c.out.strip().rstrip('cdo')

    click.echo(crayons.normal('Opening {0!r} in your EDITOR.'.format(p), bold=True))
    click.edit(filename=p)
    sys.exit(0)
cli.py 文件源码 项目:gimel 作者: Alephbet 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def configure():
    from config import config, config_filename, generate_config
    if not config:
        logger.info('generating new config {}'.format(config_filename))
        generate_config(config_filename)
    click.edit(filename=config_filename)
config_file.py 文件源码 项目:DataFS 作者: ClimateImpactLab 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def edit_config_file(self):

        click.edit(filename=self.config_file)
config.py 文件源码 项目:farmer 作者: vmfarms 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def edit(ctx):
    """
    Edit your Farmer configuration file.
    """
    config = ctx.obj['config']
    click.edit(filename=config._sources[1].yaml_filename)
__main__.py 文件源码 项目:click-man 作者: click-contrib 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def commit(repo, files, message):
    """Commits outstanding changes.

    Commit changes to the given files into the repository.  You will need to
    "repo push" to push up your changes to other repositories.

    If a list of files is omitted, all changes reported by "repo status"
    will be committed.
    """
    if not message:
        marker = '# Files to be committed:'
        hint = ['', '', marker, '#']
        for file in files:
            hint.append('#   U %s' % file)
        message = click.edit('\n'.join(hint))
        if message is None:
            click.echo('Aborted!')
            return
        msg = message.split(marker)[0].rstrip()
        if not msg:
            click.echo('Aborted! Empty commit message')
            return
    else:
        msg = '\n'.join(message)
    click.echo('Files to be committed: %s' % (files,))
    click.echo('Commit message:\n' + msg)
cli.py 文件源码 项目:zotero-cli 作者: jbaiter 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def read(ctx, item_id, with_note):
    """ Read an item attachment. """
    try:
        item_id = pick_item(ctx.obj, item_id)
    except ValueError as e:
        ctx.fail(e.args[0])
    read_att = None
    attachments = ctx.obj.attachments(item_id)
    if not attachments:
        ctx.fail("Could not find an attachment for reading.")
    elif len(attachments) > 1:
        click.echo("Multiple attachments available.")
        read_att = select([(att, att['data']['title'])
                           for att in attachments])
    else:
        read_att = attachments[0]

    att_path = ctx.obj.get_attachment_path(read_att)
    click.echo("Opening '{}'.".format(att_path))
    click.launch(str(att_path), wait=False)
    if with_note:
        existing_notes = list(ctx.obj.notes(item_id))
        if existing_notes:
            edit_existing = click.confirm("Edit existing note?")
            if edit_existing:
                note = pick_note(ctx, ctx.obj, item_id)
            else:
                note = None
        else:
            note = None
        note_body = click.edit(
            text=note['data']['note']['text'] if note else None,
            extension=get_extension(ctx.obj.note_format))
        if note_body and note is None:
            ctx.obj.create_note(item_id, note_body)
        elif note_body:
            note['data']['note']['text'] = note_body
            ctx.obj.save_note(note)
cli.py 文件源码 项目:zotero-cli 作者: jbaiter 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def add_note(ctx, item_id, note_format):
    """ Add a new note to an existing item. """
    if note_format:
        ctx.obj.note_format = note_format
    try:
        item_id = pick_item(ctx.obj, item_id)
    except ValueError as e:
        ctx.fail(e.args[0])
    note_body = click.edit(extension=get_extension(ctx.obj.note_format))
    if note_body:
        ctx.obj.create_note(item_id, note_body)
cli.py 文件源码 项目:zotero-cli 作者: jbaiter 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def edit_note(ctx, item_id, note_num):
    """ Edit a note. """
    try:
        item_id = pick_item(ctx.obj, item_id)
    except ValueError as e:
        ctx.fail(e.args[0])
    note = pick_note(ctx, ctx.obj, item_id, note_num)
    updated_text = click.edit(note['data']['note']['text'],
                              extension=get_extension(ctx.obj.note_format))
    if updated_text:
        note['data']['note']['text'] = updated_text
        ctx.obj.save_note(note)
__main__.py 文件源码 项目:passpy 作者: bfrascher 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def edit(ctx, pass_name):
    """Insert a new password or edit an existing one using the editor
    specified by either EDITOR or VISUAL or falling back on the
    platform default if both are not set.

    """
    try:
        data = ctx.obj.get_key(pass_name)
    except FileNotFoundError:
        data = ''
    except StoreNotInitialisedError:
        click.echo(MSG_STORE_NOT_INITIALISED_ERROR)
        return 1
    except PermissionError:
        click.echo(MSG_PERMISSION_ERROR)
        return 1

    if 'EDITOR' in os.environ:
        data = click.edit(text=data, editor=os.environ['EDITOR'])
    else:
        data = click.edit(text=data)

    if data is None:
        click.echo('Password unchanged.')
        return 1

    ctx.obj.set_key(pass_name, data, force=True)
cli.py 文件源码 项目:twtxt 作者: buckket 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def config(ctx, key, value, remove, edit):
    """Get or set config item."""
    conf = ctx.obj["conf"]

    if not edit and not key:
        raise click.BadArgumentUsage("You have to specify either a key or use --edit.")

    if edit:
        return click.edit(filename=conf.config_file)

    if remove:
        try:
            conf.cfg.remove_option(key[0], key[1])
        except Exception as e:
            logger.debug(e)
        else:
            conf.write_config()
        return

    if not value:
        try:
            click.echo(conf.cfg.get(key[0], key[1]))
        except Exception as e:
            logger.debug(e)
        return

    if not conf.cfg.has_section(key[0]):
        conf.cfg.add_section(key[0])

    conf.cfg.set(key[0], key[1], value)
    conf.write_config()
cli.py 文件源码 项目:nom 作者: frnsys 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def clip(save, edit, view, overwrite):
    """convert html in the clipboard to markdown"""
    path = save
    html = get_clipboard_html()
    if html is None:
        click.echo('No html in the clipboard')
        return

    if path is None:
        content = html2md.html_to_markdown(html).strip()
        click.echo(content)
        return

    if not path.endswith('.md'):
        click.echo('Note must have extension ".md"')
        return

    note = util.abs_path(path)
    if os.path.exists(note) and not overwrite:
        click.echo('Note already exists at "{}" (specify `--overwrite` to overwrite)'.format(note))
        return

    html = parsers.rewrite_external_images(html, note)
    content = html2md.html_to_markdown(html).strip()
    with open(note, 'w') as f:
        f.write(content)

    if edit:
        click.edit(filename=note)

    if view:
        compile_note(note, '/tmp', view=True)
cli.py 文件源码 项目:client 作者: wandb 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def editor(content='', marker='# Enter a description, markdown is allowed!\n'):
    message = click.edit(content + '\n\n' + marker)
    if message is not None:
        return message.split(marker, 1)[0].rstrip('\n')
sync.py 文件源码 项目:client 作者: wandb 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def editor(content='', marker='# Before we start this run, enter a brief description. (to skip, direct stdin to dev/null: `python train.py < /dev/null`)\n'):
    message = click.edit(content + '\n\n' + marker)
    if message is None:
        return None
    return message.split(marker, 1)[0].rstrip('\n')
toot.py 文件源码 项目:tootstream 作者: magicalraccoon 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def edittoot():
    edited_message = click.edit()
    if edited_message:
        return edited_message
    return ''


#####################################
######## DECORATORS          ########
#####################################
io.py 文件源码 项目:jira_pub_sync 作者: d-lobanov 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def edit_unsync_issues(cls, issues):
        """
        Allows a user to manage all new tasks. They can have three statuses: migrate, skip and hide.
        """

        MARKER = """
# Commands:
# m = migrate issue.
# s = skip issue for this time (also you can just remove the line).
# h = hide issue (skip and never migrate).
        """

        max_len = max([len(issue.fields.summary) for issue in issues])
        max_len = max_len if max_len < 200 else 200

        def line_format(issue):
            summary = cls.truncate_summary(issue.fields.summary, max_len).ljust(max_len + 2)

            return 'm  ' + issue.key + '\t' + summary + '  ' + issue.permalink()

        items = [line_format(issue) for issue in issues]

        while True:
            message = click.edit("\n".join(items) + '\n\n' + MARKER)
            if message is None:
                raise Abort

            lines = message.split(MARKER, 1)[0].rstrip('\n').split('\n')
            if lines == ['']:
                raise Abort

            try:
                return cls._read_unsync_issues(lines, issues)
            except InputException as e:
                cls.error(e.message, nl=True)
                click.pause()

                continue
reply.py 文件源码 项目:ghutil 作者: jwodder 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def cli(issue, file):
    """
    Comment on an issue/PR.

    If a file is given on the command line, its contents will be used as the
    comment body.  Otherwise, an editor will be opened for you to type your
    comment.
    """
    if file is None:
        body = click.edit()
        if body is None:
            click.echo('No text entered; exiting')
    else:
        body = file.read()
    issue.comments.post(json={"body": body})
reply.py 文件源码 项目:ghutil 作者: jwodder 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def cli(issue, file):
    """
    Comment on an issue/PR.

    If a file is given on the command line, its contents will be used as the
    comment body.  Otherwise, an editor will be opened for you to type your
    comment.
    """
    if file is None:
        body = click.edit()
        if body is None:
            click.echo('No text entered; exiting')
    else:
        body = file.read()
    issue.comments.post(json={"body": body})
edit.py 文件源码 项目:ghutil 作者: jwodder 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def edit_as_mail(obj: dict, fields=None, bodyfield=None):
    # Returns only the fields that changed
    # Fields that the user deletes are considered unchanged
    if fields is None:
        fields = sorted(obj.keys())
        if bodyfield is not None:
            fields.remove(bodyfield)
    elif isinstance(fields, str):
        fields = fields.split()
    parser = HeaderParser(body=False if bodyfield is None else None)
    msg = ''
    for f in fields:
        dispname = f.replace('_', '-').title()
        val = obj[f]
        if val is None:
            msg += '{}: \n'.format(dispname, val)
            parser.add_field(dispname, dest=f)
        elif isinstance(val, bool):
            msg += '{}: {}\n'.format(dispname, 'yes' if val else 'no')
            parser.add_field(dispname, type=BOOL, dest=f)
        elif isinstance(val, str):
            msg += '{}: {}\n'.format(dispname, val)
            parser.add_field(dispname, dest=f)
        elif isinstance(val, (list, tuple)):
            msg += '{}: {}\n'.format(dispname, ', '.join(map(str, val)))
            parser.add_field(dispname, type=LIST, dest=f)
        else:
            raise TypeError('only string, boolean, and list fields supported')
    if bodyfield is not None:
        msg += '\n' + (obj[bodyfield] or '')
    msg = click.edit(msg, require_save=True)
    if msg is None:
        return None
    data = parser.parse_string(msg)
    newobj = dict(data)
    if data.body is not None:
        newobj[bodyfield] = data.body
    for k,v in list(newobj.items()):
        if (list(obj[k]) if isinstance(obj[k], tuple) else obj[k]) == v or \
                obj[k] is None and v == '':
            del newobj[k]
    return newobj


问题


面经


文章

微信
公众号

扫码关注公众号