Python click.confirm() Examples
The following are 30
code examples of click.confirm().
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
click
, or try the search function
.
Example #1
Source File: send_email.py From airflow with Apache License 2.0 | 7 votes |
def inter_send_email( username: str, password: str, sender_email: str, receiver_email: Union[str, List], message: str ): """ Send email using SMTP """ show_message("SMTP", message) click.confirm("Is the Email message ok?", abort=True) try: send_email( SMTP_SERVER, SMTP_PORT, username, password, sender_email, receiver_email, message, ) click.secho("✅ Email sent successfully", fg="green") except smtplib.SMTPAuthenticationError: sys.exit("SMTP User authentication error, Email not sent!") except Exception as e: # pylint: disable=broad-except sys.exit(f"SMTP exception {e}")
Example #2
Source File: send_email.py From airflow with Apache License 2.0 | 6 votes |
def vote(base_parameters, receiver_email: str): """ Send email calling for Votes on RC """ template_file = "templates/vote_email.j2" base_parameters.template_arguments["receiver_email"] = receiver_email message = render_template(template_file, **base_parameters.template_arguments) inter_send_email( base_parameters.username, base_parameters.password, base_parameters.template_arguments["sender_email"], base_parameters.template_arguments["receiver_email"], message, ) if click.confirm("Show Slack message for announcement?", default=True): base_parameters.template_arguments["slack_rc"] = False slack_msg = render_template("templates/slack.j2", **base_parameters.template_arguments) show_message("Slack", slack_msg)
Example #3
Source File: cli.py From Watson with MIT License | 6 votes |
def remove(watson, id, force): """ Remove a frame. You can specify the frame either by id or by position (ex: `-1` for the last frame). """ frame = get_frame_from_argument(watson, id) id = frame.id if not force: click.confirm( u"You are about to remove frame " u"{project}{tags} from {start} to {stop}, continue?".format( project=style('project', frame.project), tags=(" " if frame.tags else "") + style('tags', frame.tags), start=style('time', '{:HH:mm}'.format(frame.start)), stop=style('time', '{:HH:mm}'.format(frame.stop)) ), abort=True ) del watson.frames[id] watson.save() click.echo("Frame removed.")
Example #4
Source File: vcm.py From vcm with GNU General Public License v3.0 | 6 votes |
def nmap(): try: project_config = VcmProjectConfig() project_config.read_project_vcm() except ValueError as ex: print(ex) return # We only need the netloc of the full url - strip the rest out nmap_targets = [] for t in project_config.targets: nmap_targets.append(urlparse(t).netloc) if not click.confirm('Run nmap against the following targets: %s' % ', '.join(nmap_targets)): return args = ["nmap"] args.extend(DEFAULT_NMAP_SETTINGS) for t in nmap_targets: args.append(t) args.append("-oA") args.append(os.path.join(project_config.artifacts_folder, f'nmap_{time.time()}')) call(args)
Example #5
Source File: vcm.py From vcm with GNU General Public License v3.0 | 6 votes |
def nikto(): try: project_config = VcmProjectConfig() project_config.read_project_vcm() except ValueError as ex: print(ex) return if not click.confirm('Run nikto against the following targets: %s' % ', '.join(project_config.targets)): return # Nikto takes multiple hosts from a file # BUT bear in mind advice from: https://github.com/sullo/nikto/wiki/Basic-Testing # ie run scans separately so that memory is freed each time. for t in project_config.targets: output_filename = os.path.join(project_config.artifacts_folder, f"nikto_{urlparse(t).netloc}_{time.time()}.html") try: # nikto -h https://www.test.com -ssl -Format html -output . args = ["nikto", "-h", t, '-ssl', '-Format', 'html', '-output', output_filename] print(args) call(args) except Exception as ex: print(f"Error writing nikto output to: {output_filename} : {ex}")
Example #6
Source File: experiment.py From floyd-cli with Apache License 2.0 | 6 votes |
def stop(id): """ Stop a running job. """ try: experiment = ExperimentClient().get(normalize_job_name(id)) except FloydException: experiment = ExperimentClient().get(id) if experiment.state not in ["queued", "queue_scheduled", "running"]: floyd_logger.info("Job in {} state cannot be stopped".format(experiment.state)) sys.exit(1) if not ExperimentClient().stop(experiment.id): floyd_logger.error("Failed to stop job") sys.exit(1) floyd_logger.info("Experiment shutdown request submitted. Check status to confirm shutdown")
Example #7
Source File: cli.py From invenio-app-ils with MIT License | 6 votes |
def index_json(filenames, force): """Index JSON-based vocabularies in Elasticsearch.""" if not force: click.confirm( "Are you sure you want to index the vocabularies?", abort=True ) source = "json" index_count = 0 for filename in filenames: click.echo('indexing vocabularies in {}...'.format(filename)) vocabularies = load_vocabularies(source, filename) cfg = current_app.config["RECORDS_REST_ENDPOINTS"][VOCABULARY_PID_TYPE] indexer = cfg["indexer_class"]() with click.progressbar(vocabularies) as bar: for vocabulary in bar: indexer.index(vocabulary) index_count += len(vocabularies) click.echo('indexed {} vocabularies'.format(index_count))
Example #8
Source File: cli.py From invenio-app-ils with MIT License | 6 votes |
def index_opendefinition(loader, path, whitelist_status, force): """Index JSON-based vocabularies in Elasticsearch.""" if not force: click.confirm( "Are you sure you want to index the vocabularies?", abort=True ) index_count = 0 click.echo('indexing licenses from loader {} and path {}...'.format( loader, path )) if whitelist_status: whitelist_status = whitelist_status.split(",") vocabularies = load_vocabularies( "opendefinition", loader, path, whitelist_status ) cfg = current_app.config["RECORDS_REST_ENDPOINTS"][VOCABULARY_PID_TYPE] indexer = cfg["indexer_class"]() with click.progressbar(vocabularies) as bar: for vocabulary in bar: indexer.index(vocabulary) index_count += len(vocabularies) click.echo('indexed {} licenses'.format(index_count))
Example #9
Source File: cli.py From invenio-app-ils with MIT License | 6 votes |
def delete(type, force, key): """Delete indexed vocabularies.""" count = delete_vocabulary_from_index(type=type, force=force, key=key) if not force: if count == 0: click.secho("No vocabularies found. Exiting.") exit(1) if click.confirm( "You are about to delete {} vocabularies of type '{}'. " "Do you want to continue?".format(count, type), abort=True ): count = delete_vocabulary_from_index( type=type, force=True, key=key) click.echo('deleted {} vocabularies'.format(count))
Example #10
Source File: testCompilerUploader.py From web2board with GNU Lesser General Public License v3.0 | 6 votes |
def setUpClass(cls): if cls.portToUse is None: try: cls.portToUse = CompilerUploader.construct(cls.__get_platform_to_use()).get_port() except: cls.portToUse = -1 cls.platform_to_use = cls.__get_platform_to_use() log.info("""\n\n ####################################### Remember to connect a {} board #######################################\n""".format(cls.platform_to_use)) def click_confirm(message): print message return True click.confirm = click_confirm
Example #11
Source File: run.py From web2board with GNU Lesser General Public License v3.0 | 6 votes |
def _autoinstall_libs(ctx, libids_list): require_libs = [int(l.strip()) for l in libids_list.split(",")] installed_libs = [ l['id'] for l in LibraryManager().get_installed().values() ] not_intalled_libs = set(require_libs) - set(installed_libs) if not require_libs or not not_intalled_libs: return if (not app.get_setting("enable_prompts") or click.confirm( "The libraries with IDs '%s' have not been installed yet. " "Would you like to install them now?" % ", ".join([str(i) for i in not_intalled_libs]) )): ctx.invoke(cmd_lib_install, libid=not_intalled_libs)
Example #12
Source File: helper.py From twtxt with MIT License | 6 votes |
def validate_text(ctx, param, value): conf = click.get_current_context().obj["conf"] if isinstance(value, tuple): value = " ".join(value) if not value and not sys.stdin.isatty(): value = click.get_text_stream("stdin").read() if value: value = value.strip() if conf.character_warning and len(value) > conf.character_warning: click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format( conf.character_warning), abort=True) return value else: raise click.BadArgumentUsage("Text can’t be empty.")
Example #13
Source File: tag.py From acsoo with GNU General Public License v3.0 | 6 votes |
def do_tag(config, force, src, requirement, yes, dry_run=False): tag = config.version if not yes: click.confirm("Tag project with {}?".format(tag), abort=True) if force: force_cmd = ["-f"] else: force_cmd = [] if call(["git", "diff", "--exit-code"]) != 0: raise click.ClickException("Please commit first.") if call(["git", "diff", "--exit-code", "--cached"]) != 0: raise click.ClickException("Please commit first.") out = check_output( ["git", "ls-files", "--other", "--exclude-standard", "--directory"] ) if out: click.echo(out) raise click.ClickException("Please commit first.") do_tag_requirements(config, src, requirement, yes=True, dry_run=dry_run) click.echo("placing tag {tag} on origin".format(**locals())) if not dry_run: check_call(["git", "tag"] + force_cmd + [tag]) check_call(["git", "push", "-q"] + force_cmd + ["origin", "tag", tag])
Example #14
Source File: apply.py From dcos-deploy with Apache License 2.0 | 6 votes |
def apply(config_file, var, only, dry_run, yes, debug, force): global_config.debug = debug provided_variables = get_variables(var) if not config_file: config_file = detect_yml_file("dcos") runner = DeploymentRunner(config_file, provided_variables) if only: if runner.partial_dry_run(only, force=force) and not dry_run: if yes or click.confirm("Do you want to apply these changes?", default=False): runner.run_partial_deployment(only, force=force) else: echo("Not doing anything") else: if runner.dry_run() and not dry_run: if yes or click.confirm("Do you want to apply these changes?", default=False): runner.run_deployment(force=force) else: echo("Not doing anything")
Example #15
Source File: delete.py From dcos-deploy with Apache License 2.0 | 6 votes |
def delete(config_file, var, only, dry_run, yes): provided_variables = get_variables(var) if not config_file: config_file = detect_yml_file("dcos") runner = DeletionRunner(config_file, provided_variables) if only: if runner.partial_dry_run(only) and not dry_run: if yes or click.confirm("Do you want to apply these changes?", default=False): runner.run_partial_deletion(only) else: echo("Not doing anything") else: if runner.dry_run() and not dry_run: if yes or click.confirm("Do you want to apply these changes?", default=False): runner.run_deletion() else: echo("Not doing anything")
Example #16
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 6 votes |
def uninstall(ctx): oo_cfg = ctx.obj['oo_cfg'] verbose = ctx.obj['verbose'] if hasattr(oo_cfg, 'deployment'): hosts = oo_cfg.deployment.hosts elif hasattr(oo_cfg, 'hosts'): hosts = oo_cfg.hosts else: click.echo("No hosts defined in: %s" % oo_cfg.config_path) sys.exit(1) click.echo("OpenShift will be uninstalled from the following hosts:\n") if not ctx.obj['unattended']: # Prompt interactively to confirm: for host in hosts: click.echo(" * %s" % host.connect_to) proceed = click.confirm("\nDo you want to proceed?") if not proceed: click.echo("Uninstall cancelled.") sys.exit(0) openshift_ansible.run_uninstall_playbook(hosts, verbose)
Example #17
Source File: drawingdataset.py From cartoonify with MIT License | 6 votes |
def setup(self): try: with jsonlines.open(self._category_mapping_filepath, mode='r') as reader: self._category_mapping = reader.read() except IOError as e: self._logger.exception(e) print('label_mapping.jsonl not found') raise e self._categories = self.load_categories(self._path) if not self._categories: if click.confirm('no drawings available, would you like to download the dataset? ' 'download will take approx 5gb of space'): self.download_recurse(self._quickdraw_dataset_url, self._path) self._categories = self.load_categories(self._path) else: self._logger.error('no drawings available, and user declined to download dataset') raise ValueError('no drawings available, please download dataset')
Example #18
Source File: cli.py From cfn-sphere with Apache License 2.0 | 6 votes |
def encrypt(region, keyid, cleartext, context, confirm, yes): confirm = confirm or yes if not confirm: check_update_available() try: cipertext = KMS(region).encrypt(keyid, cleartext, kv_list_to_dict(context)) click.echo("Ciphertext: {0}".format(cipertext)) except CfnSphereException as e: LOGGER.error(e) sys.exit(1) except Exception as e: LOGGER.error("Failed with unexpected error") LOGGER.exception(e) LOGGER.info("Please report at https://github.com/cfn-sphere/cfn-sphere/issues!") sys.exit(1)
Example #19
Source File: cli.py From cfn-sphere with Apache License 2.0 | 6 votes |
def decrypt(region, ciphertext, context, confirm, yes): confirm = confirm or yes if not confirm: check_update_available() try: cleartext = KMS(region).decrypt(ciphertext, kv_list_to_dict(context)) click.echo("Cleartext: {0}".format(cleartext)) except CfnSphereException as e: LOGGER.error(e) sys.exit(1) except Exception as e: LOGGER.error("Failed with unexpected error") LOGGER.exception(e) LOGGER.info("Please report at https://github.com/cfn-sphere/cfn-sphere/issues!") sys.exit(1)
Example #20
Source File: cli.py From twtxt with MIT License | 6 votes |
def follow(ctx, nick, url, force): """Add a new source to your followings.""" source = Source(nick, url) sources = ctx.obj['conf'].following if not force: if source.nick in (source.nick for source in sources): click.confirm("➤ You’re already following {0}. Overwrite?".format( click.style(source.nick, bold=True)), default=False, abort=True) _, status = get_remote_status([source])[0] if not status or status.status_code != 200: click.confirm("➤ The feed of {0} at {1} is not available. Follow anyway?".format( click.style(source.nick, bold=True), click.style(source.url, bold=True)), default=False, abort=True) ctx.obj['conf'].add_source(source) click.echo("✓ You’re now following {0}.".format( click.style(source.nick, bold=True)))
Example #21
Source File: cli.py From catt with BSD 2-Clause "Simplified" License | 6 votes |
def save(settings, path): cst = setup_cast(settings["device"], prep="control") if not cst.save_capability or cst.is_streaming_local_file: raise CliError("Saving state of this kind of content is not supported") elif cst.save_capability == "partial": echo_warning("Please be advised that playlist data will not be saved") echo_status(cst.media_info) if path and path.is_file(): click.confirm("File already exists. Overwrite?", abort=True) click.echo("Saving...") if path: state = CastState(path, StateMode.ARBI) cc_name = "*" else: state = CastState(STATE_PATH, StateMode.CONF) cc_name = cst.cc_name state.set_data(cc_name, {"controller": cst.name, "data": cst.media_info})
Example #22
Source File: prompt_utils.py From pgcli with BSD 3-Clause "New" or "Revised" License | 5 votes |
def confirm(*args, **kwargs): """Prompt for confirmation (yes/no) and handle any abort exceptions.""" try: return click.confirm(*args, **kwargs) except click.Abort: return False
Example #23
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def confirm_continue(message): if message: click.echo(message) click.confirm("Are you ready to continue?", default=False, abort=True) return
Example #24
Source File: methods.py From dyc with MIT License | 5 votes |
def polish(self): """ Editor wrapper to confirm result """ docstring = self.result.split("\n") polished = "\n".join([self.leading_space + docline for docline in docstring]) if self.placeholders: self.result = polished else: self.confirm(polished)
Example #25
Source File: imageprocessor.py From cartoonify with MIT License | 5 votes |
def setup(self): self._logger = logging.getLogger(self.__class__.__name__) if not Path(self._path_to_model).exists(): if click.confirm('no object detection model available, would you like to download the model? ' 'download will take approx 100mb of space'): self.download_model(self._download_url, self._model_name + '.tar.gz') self.load_model(self._path_to_model) self._labels = self.load_labels(self._path_to_labels) # run a detection once, because first model run is always slow self.detect(np.ones((150, 150, 3), dtype=np.uint8))
Example #26
Source File: wipe.py From edgedb with Apache License 2.0 | 5 votes |
def wipe(*, postgres_dsn, data_dir, yes, dry_run): if postgres_dsn: cluster = pgcluster.get_remote_pg_cluster(postgres_dsn) elif data_dir: cluster = pgcluster.get_local_pg_cluster(data_dir) cluster.set_connection_params( pgconnparams.ConnectionParameters( user='postgres', database='template1', ), ) else: raise click.UsageError( 'either --postgres-dsn or --data-dir is required' ) if not yes and not click.confirm( 'This will DELETE all EdgeDB data from the target ' 'PostgreSQL instance. ARE YOU SURE?'): click.echo('OK. Not proceeding.') status = cluster.get_status() cluster_started_by_us = False if status != 'running': if isinstance(cluster, pgcluster.RemoteCluster): click.secho(f'Remote cluster is not running', fg='red') sys.exit(1) else: cluster.start(port=edbcluster.find_available_port()) cluster_started_by_us = True try: asyncio.run(do_wipe(cluster, dry_run)) finally: if cluster_started_by_us: cluster.stop()
Example #27
Source File: command_line.py From Dallinger with MIT License | 5 votes |
def compensate(recruiter, worker_id, email, dollars, sandbox): """Credit a specific worker by ID through their recruiter""" out = Output() config = get_config() config.load() mode = "sandbox" if sandbox else "live" do_notify = email is not None no_email_str = "" if email else " NOT" with config.override({"mode": mode}): rec = by_name(recruiter) if not click.confirm( '\n\nYou are about to pay worker "{}" ${:.2f} in "{}" mode using the "{}" recruiter.\n' "The worker will{} be notified by email. " "Continue?".format(worker_id, dollars, mode, recruiter, no_email_str) ): out.log("Aborting...") return try: result = rec.compensate_worker( worker_id=worker_id, email=email, dollars=dollars, notify=do_notify ) except Exception as ex: out.error( "Compensation failed. The recruiter reports the following error:\n{}".format( ex ), delay=0, ) return out.log("HIT Details", delay=0) out.log(tabulate.tabulate(result["hit"].items()), chevrons=False, delay=0) out.log("Qualification Details", delay=0) out.log(tabulate.tabulate(result["qualification"].items()), chevrons=False, delay=0) out.log("Worker Notification", delay=0) out.log(tabulate.tabulate(result["email"].items()), chevrons=False, delay=0)
Example #28
Source File: command_line.py From Dallinger with MIT License | 5 votes |
def revoke(workers, qualification, by_name, reason, sandbox): """Revoke a qualification from 1 or more workers""" if not (workers and qualification): raise click.BadParameter( "Must specify a qualification ID or name, and at least one worker ID" ) mturk = _mturk_service_from_config(sandbox) if by_name: result = mturk.get_qualification_type_by_name(qualification) if result is None: raise click.BadParameter( 'No qualification with name "{}" exists.'.format(qualification) ) qid = result["id"] else: qid = qualification if not click.confirm( '\n\nYou are about to revoke qualification "{}" ' "for these workers:\n\t{}\n\n" "This will send an email to each of them from Amazon MTurk. " "Continue?".format(qid, "\n\t".join(workers)) ): click.echo("Aborting...") return for worker in workers: if mturk.revoke_qualification(qid, worker, reason): click.echo( 'Revoked qualification "{}" from worker "{}"'.format(qid, worker) ) # print out the current set of workers with the qualification results = list(mturk.get_workers_with_qualification(qid)) click.echo( 'There are now {} workers with qualification "{}"'.format(len(results), qid) )
Example #29
Source File: utils.py From isitfit with Apache License 2.0 | 5 votes |
def ask_feedback(): # TODO should use a proper feedback gathering method rather than collecting it in matomo # but this is a shortcut for now print("") import click a1 = click.prompt("How useful was this? (0: wtf, 1: useless, 2: IDK, 3: kind of, 4: epiphanic)", type=click.IntRange(0, 4)) ping_matomo("/feedback?a1_usefulness=%i"%a1) q2 = { 0: "Seriously? Why?", 1: "Is there no hope? What can be done?", 2: "What would make things clearer?", 3: "What can we improve?", 4: "TBH, I wasn't expecting this. Really? Why?" } a2 = click.prompt(q2[a1]) ping_matomo("/feedback?a2_why=%s"%a2) a3a = click.confirm("Shall we schedule a 10-minute phone call?") ping_matomo("/feedback?a3a_can_we_call=%s"%b2l(a3a)) a3b = None a3c = None if a3a: a3b = click.prompt("Phone number with country code") ping_matomo("/feedback?a3b_phone=%s"%a3b) a3c = click.prompt("Best time to call (include timezone)") ping_matomo("/feedback?a3c_time=%s"%a3c) print("Perfect! In the mean time, feel free to reach me at shadi@autofitcloud.com") else: print("Ok. You can always reach me at shadi@autofitcloud.com") print("Thanks!")
Example #30
Source File: prompt_utils.py From pgcli with BSD 3-Clause "New" or "Revised" License | 5 votes |
def confirm_destructive_query(queries): """Check if the query is destructive and prompts the user to confirm. Returns: * None if the query is non-destructive or we can't prompt the user. * True if the query is destructive and the user wants to proceed. * False if the query is destructive and the user doesn't want to proceed. """ prompt_text = ( "You're about to run a destructive command.\n" "Do you want to proceed? (y/n)" ) if is_destructive(queries) and sys.stdin.isatty(): return prompt(prompt_text, type=bool)