本文整理匯總了Python中click.edit方法的典型用法代碼示例。如果您正苦於以下問題:Python click.edit方法的具體用法?Python click.edit怎麽用?Python click.edit使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類click
的用法示例。
在下文中一共展示了click.edit方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: edit_node_description
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def edit_node_description(ctx, name):
"""
Interactively edit the node description and save.
NAME must be the name of a node that you own.
Open the text editor specified by the EDITOR environment variable
with the current node description. If you save and exit, the changes
will be applied to the node.
"""
client = ControllerClient()
node = client.find_node(name)
if node is None:
click.echo("Node {} was not found.".format(name))
return
description = click.edit(node.get('description', ''))
if description is None:
click.echo("No change made.")
else:
node['description'] = description
result = client.save_node(node)
click.echo(util.format_result(result))
return result
示例2: format_yaml
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def format_yaml(file, namespace, edit=False, print=True, extra=[]):
env = {"NAMESPACE": namespace}
env.update(**dict(extra))
manifest = formatter.format(file, env)
if edit:
manifest = click.edit(manifest)
if manifest is None:
click.echo("File not saved, aborting")
return
elif print:
click.echo(manifest)
return manifest
示例3: deploy
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def deploy(ctx, file, namespace, edit, wait, timeout, **kwargs):
manifest = format_yaml(file, namespace, edit=edit, extra=kwargs["set"])
result = deploy_from_manifest(ctx, namespace, manifest)
if not wait or result != 0:
sys.exit(result)
if timeout == 0:
timeout = None
try:
wait_for_rolling_deploy(ctx, namespace, manifest, timeout)
except subprocess.CalledProcessError as e:
print_error("Improper exit with code " + str(e.returncode) + ", exiting...")
sys.exit(3)
except subprocess.TimeoutExpired:
print_error("Rollout took too long, exiting...")
sys.exit(2)
示例4: app_edit
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def app_edit(api, app):
data = api.get(f"/apps/{app}/")
# id isn't editable
data.pop("id")
rv = click.edit(json.dumps(data, indent=2) + "\n")
if rv is None:
return
rv = json.loads(rv)
params = {}
for k, v in rv.items():
if isinstance(v, (list, dict)):
params[k] = json.dumps(v)
else:
params[k] = v
api.put(f"/apps/{app}/", params)
click.echo(f"App {app} was updated.")
示例5: add_card
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def add_card(ctx, title, message, edit, listname):
'''Add a new card. If no title is provided, $EDITOR will be opened so you can write one.'''
connection = ctx.connection
if listname is None:
inbox = connection.inbox_list()
else:
pattern = re.compile(listname, flags=re.I)
target_lists = filter(lambda x: pattern.search(x.name), ctx.board.get_lists('open'))
try:
inbox = next(target_lists)
except StopIteration:
click.secho(f'No list names matched by {listname}', fg='red')
raise GTDException(1)
if not title:
title = click.edit(require_save=True, text='<Title here>')
if title is None: # No changes were made in $EDITOR
click.secho('No title entered for the new card!', fg='red')
raise GTDException(1)
else:
title = title.strip()
returned = inbox.add_card(name=title, desc=message)
if edit:
ctx.card_repl(returned)
else:
click.secho(f'Successfully added card "{returned.name}"!', fg='green')
示例6: load_editor
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def load_editor():
marker = (
"# Everything below this line is ignored\n"
"Write title in first line, then content in next paragraph\n"
)
message = click.edit("\n\n" + marker)
try:
message = message.split(marker, 1)[0].rstrip("\n")
if not message:
raise ValueError
except Exception:
click.secho(":: ERROR empty file. Aborting...", bold=True, fg="bright_red")
raise SystemExit()
title_content = message.split("\n\n", maxsplit=1)
title = title_content[0]
content = ""
if len(title_content) > 1:
content = title_content[1]
title, content = [i.strip() for i in (title, content)]
return title, content
示例7: config
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
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()
示例8: bumpversion
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def bumpversion(ctx, part, allow_dirty, force, yes):
args = [part]
allow_dirty = allow_dirty or force
is_clean = is_git_clean(ctx.obj['base_path'])
if not is_clean and not allow_dirty:
print('')
print('ERROR: Git working directory is not clean.')
print('')
print('You can use --allow-dirty or --force if you know what '
'you\'re doing.')
exitcode = 1
else:
if allow_dirty:
args.append('--allow-dirty')
command = ['bumpversion'] + args
old_version = get_version(ctx.obj['package_path'])
exitcode = subprocess.call(command, cwd=ctx.obj['base_path'])
new_version = get_version(ctx.obj['package_path'])
if exitcode == 0:
print('Bump version from {old} to {new}'.format(
old=old_version, new=new_version))
if yes or click.confirm('Do you want to edit CHANGES.md?'):
click.edit(filename=os.path.join(ctx.obj['base_path'], 'CHANGES.md'))
sys.exit(exitcode)
示例9: editor
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def editor():
"""Launch an editor."""
message = click.edit("Prepopulated text")
click.echo("Your message: {}".format(message))
示例10: edit_config
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def edit_config(config_file):
if config_file:
click.edit(filename=config_file)
示例11: configure
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def configure():
if not config:
logger.info('generating new config {}'.format(config_filename))
generate_config(config_filename)
click.edit(filename=config_filename)
示例12: edit
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
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 StoreNotInitialisedError:
click.echo(MSG_STORE_NOT_INITIALISED_ERROR)
return 1
except FileNotFoundError:
data = ''
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)
示例13: open_external_editor
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def open_external_editor(filename=None, sql=None):
"""Open external editor, wait for the user to type in their query, return
the query.
:return: list with one tuple, query as first element.
"""
message = None
filename = filename.strip().split(" ", 1)[0] if filename else None
sql = sql or ""
MARKER = "# Type your query above this line.\n"
# Populate the editor buffer with the partial sql (if available) and a
# placeholder comment.
query = click.edit(
"{sql}\n\n{marker}".format(sql=sql, marker=MARKER),
filename=filename,
extension=".sql",
)
if filename:
try:
with open(filename, encoding="utf-8") as f:
query = f.read()
except IOError:
message = "Error reading file: %s." % filename
if query is not None:
query = query.split(MARKER, 1)[0].rstrip("\n")
else:
# Don't return None for the caller to deal with.
# Empty string is ok.
query = sql
return (query, message)
示例14: open_external_editor
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
def open_external_editor(filename=None, sql=None):
"""
Open external editor, wait for the user to type in his query,
return the query.
:return: list with one tuple, query as first element.
"""
message = None
filename = filename.strip().split(' ', 1)[0] if filename else None
sql = sql or ''
MARKER = '# Type your query above this line.\n'
# Populate the editor buffer with the partial sql (if available) and a
# placeholder comment.
query = click.edit(u'{sql}\n\n{marker}'.format(sql=sql, marker=MARKER),
filename=filename, extension='.sql')
if filename:
try:
query = read_from_file(filename)
except IOError:
message = 'Error reading file: %s.' % filename
if query is not None:
query = query.split(MARKER, 1)[0].rstrip('\n')
else:
# Don't return None for the caller to deal with.
# Empty string is ok.
query = sql
return (query, message)
示例15: read
# 需要導入模塊: import click [as 別名]
# 或者: from click import edit [as 別名]
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)