Python click.Abort() Examples

The following are 30 code examples of click.Abort(). 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: panels.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def panels(institute):
    """Show all gene panels in the database"""
    LOG.info("Running scout view panels")
    adapter = store

    panel_objs = [panel for panel in adapter.gene_panels(institute_id=institute)]
    if len(panel_objs) == 0:
        LOG.info("No panels found")
        raise click.Abort()
    click.echo("#panel_name\tversion\tnr_genes\tdate")

    for panel_obj in panel_objs:
        click.echo(
            "{0}\t{1}\t{2}\t{3}".format(
                panel_obj["panel_name"],
                str(panel_obj["version"]),
                len(panel_obj["genes"]),
                str(panel_obj["date"].strftime("%Y-%m-%d")),
            )
        ) 
Example #2
Source File: hlsclt.py    From hlsclt with MIT License 6 votes vote down vote up
def cli(ctx):
    """Helper tool for using Vivado HLS through the command line. If no arguments are specified then a default run is executed which includes C simulation, C synthesis, Cosimulation and export for both Vivado IP Catalog and System Generator. If any of the run options are specified then only those specified are performed."""
    # Generate a default config dict and then load in the local config file.
    config = generate_default_config();
    config_loaded = get_vars_from_file('hls_config.py')
    errors = []
    parse_config_vars(config_loaded, config, errors)
    if len(errors) != 0:
        for err in errors:
            print(err)
        print("Config Errors, exiting...")
        raise click.Abort()
    # Store the loaded config in an object within the Click context so it is available to all commands.
    obj = hlsclt_internal_object(config)
    ctx.obj = obj
    pass

# Add Click Sub Commands 
Example #3
Source File: init.py    From agogosml with MIT License 6 votes vote down vote up
def init(force, project_name, cloud_vendor, folder) -> int:
    """Initializes an agogosml project by creating a manifest file"""
    # Check if exists
    folder = Path(folder)
    outfile = folder / 'manifest.json'
    if outfile.is_file():
        if force:
            click.echo('Overwriting %s' % outfile)
        else:
            click.echo('Manifest already exists. Use --force to overwrite')
            raise click.Abort()
    # Create folder if not exists
    outfile.parent.mkdir(parents=True, exist_ok=True)
    manifest = build_manifest(project_name, cloud_vendor)
    with outfile.open('w') as fobj:
        json.dump(manifest, fobj, indent=4)
    return 0 
Example #4
Source File: cli.py    From ricloud with GNU Lesser General Public License v3.0 6 votes vote down vote up
def init(token, url=None):
    """Helper to initialise the ricloud client's local configuration."""
    from ricloud import conf

    conf_path = conf.get_user_root_config_path()

    if os.path.exists(conf_path):
        click.secho(
            "ricloud configuration already exists at: {}".format(conf_path), fg="red"
        )
        raise click.Abort

    settings = conf.settings
    settings.set("api", "token", token)

    if url:
        settings.set("api", "url", url)

    with open(conf_path, "w") as conf_file:
        settings.write(conf_file)

    click.secho("ricloud configuration created at: {}".format(conf_path), fg="green") 
Example #5
Source File: build_commands.py    From hlsclt with MIT License 6 votes vote down vote up
def build_end_callback(ctx,sub_command_returns,keep,report):
    # Catch the case where no subcommands have been issued and offer a default build
    if not sub_command_returns:
        if click.confirm("No build stages specified, would you like to run a default sequence using all the build stages?", abort=True):
            do_default_build(ctx)
    ctx.obj.file.write("exit" + "\n")
    ctx.obj.file.close()
    # Call the Vivado HLS process
    returncode = subprocess.call(["vivado_hls -f run_hls.tcl"],shell=True)
    # Check return status of the HLS process.
    if returncode < 0:
        raise click.Abort()
    elif returncode > 0:
        click.echo("Warning: HLS Process returned an error, skipping report opening!")
        raise click.Abort()
    else:
        do_end_build_stuff(ctx,sub_command_returns,report)

# csim subcommand 
Example #6
Source File: cli.py    From passpie with MIT License 6 votes vote down vote up
def logging_exception(exceptions=[Exception]):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                return func(*args, **kwargs)
            except (click.ClickException, click.Abort):
                raise
            except tuple(exceptions) as e:
                logging_level = logging.getLogger().getEffectiveLevel()
                if logging_level == logging.DEBUG:
                    raise
                elif logging_level == logging.CRITICAL:
                    pass
                else:
                    logging.error(str(e))
                sys.exit(1)
        return wrapper
    return decorator 
Example #7
Source File: helpers.py    From ricloud with GNU Lesser General Public License v3.0 6 votes vote down vote up
def await_poll(poll):
    info("Awaiting completion of poll {} ...".format(poll.id))

    await_response(poll)

    if poll.state == "failed":
        warn("Poll failed with error: `{}`".format(poll.error))
        raise click.Abort
    elif poll.state == "pending":
        warn(
            (
                "Poll {poll_id} did not to complete within client timeout. "
                "Please retrieve it using: ricloud icloud poll retrieve {poll_id}"
            ).format(poll_id=poll["id"])
        )
    else:
        success("Poll {} completed.".format(poll.id)) 
Example #8
Source File: common.py    From xcube with MIT License 6 votes vote down vote up
def handle_cli_exception(e: BaseException, exit_code: int = None, traceback_mode: bool = False) -> int:
    import sys
    if isinstance(e, click.Abort):
        print(f'Aborted!')
        exit_code = exit_code or 1
    elif isinstance(e, click.ClickException):
        e.show(file=sys.stderr)
        exit_code = exit_code or e.exit_code
    elif isinstance(e, OSError):
        print(f'OS error: {e}', file=sys.stderr)
        exit_code = exit_code or 2
    else:
        print(f'Internal error: {e}', file=sys.stderr)
        exit_code = exit_code or 3
    if traceback_mode:
        import traceback
        traceback.print_exc(file=sys.stderr)
    return exit_code 
Example #9
Source File: AccountCreator.py    From TensorHive with Apache License 2.0 6 votes vote down vote up
def _ask_for_password(self):
        # Useful aliases
        prompt_for_password = lambda message: click.prompt(message, type=str, hide_input=True)
        password_length_requirement = 'at least {} characters'.format(self.new_user.min_password_length)
        first_password_message = '[3/4] password ({})'.format(password_length_requirement)
        repeated_password_message = '[3/4] repeat password'

        valid_password_provided = False
        while not valid_password_provided:
            try:
                password1 = prompt_for_password(message=first_password_message)
                self.new_user.password = password1
                password2 = prompt_for_password(message=repeated_password_message)
                assert password1 == password2, 'Passwords don\'t match, please try again.'
            except click.Abort:
                raise
            except Exception as error_msg:
                click.echo(str(error_msg))
            else:
                valid_password_provided = True 
Example #10
Source File: mapping.py    From followthemoney with MIT License 6 votes vote down vote up
def stream_mapping(infile, outfile, mapping_yaml, sign=True):
    sources = []
    config = load_mapping_file(mapping_yaml)
    for dataset, meta in config.items():
        for data in keys_values(meta, 'queries', 'query'):
            query = model.make_mapping(data, key_prefix=dataset)
            source = StreamSource(query, data)
            sources.append((dataset, source))

    try:
        for record in StreamSource.read_csv(infile):
            for (dataset, source) in sources:
                ns = Namespace(dataset)
                if source.check_filters(record):
                    entities = source.query.map(record)
                    for entity in entities.values():
                        if sign:
                            entity = ns.apply(entity)
                        write_object(outfile, entity)
    except BrokenPipeError:
        raise click.Abort() 
Example #11
Source File: __init__.py    From sesdev with MIT License 6 votes vote down vote up
def redeploy(deployment_id, **kwargs):
    """
    Destroys the VMs of the deployment DEPLOYMENT_ID and deploys again the cluster
    from scratch with the same configuration.
    """
    interactive = not (kwargs.get('non_interactive', False) or kwargs.get('force', False))
    if interactive:
        really_want_to = True
        if interactive:
            really_want_to = click.confirm(
                'Do you want to continue with the deployment?',
                default=True,
                )
        if not really_want_to:
            raise click.Abort()
    dep = Deployment.load(deployment_id)
    dep.destroy(_print_log)
    dep = Deployment.create(deployment_id, dep.settings)
    dep.start(_print_log) 
Example #12
Source File: __init__.py    From sesdev with MIT License 6 votes vote down vote up
def destroy(deployment_id, **kwargs):
    """
    Destroys the deployment(s) named DEPLOYMENT_SPEC -- where DEPLOYMENT_SPEC might
    be either a literal deployment ID or a glob ("octopus_*") -- by destroying the
    VMs and deleting the deployment directory.
    """
    interactive = not (kwargs.get('non_interactive', False) or kwargs.get('force', False))
    destroy_networks = kwargs.get('destroy_networks', False)
    matching_deployments = _maybe_glob_deps(deployment_id)
    cluster_word = _cluster_singular_or_plural(matching_deployments)
    if interactive:
        really_want_to = click.confirm(
            'Do you really want to destroy {} {}'.format(len(matching_deployments), cluster_word),
            default=True,
            )
        if not really_want_to:
            raise click.Abort()
    for dep in matching_deployments:
        logger.debug("destroy deployment: '%s', destroy networks: %s",
                     deployment_id,
                     destroy_networks)
        dep.destroy(_print_log, destroy_networks)
        click.echo("Deployment {} destroyed!".format(dep.dep_id)) 
Example #13
Source File: hpo.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def hpo_genes(hpo_term):
    """Export a list of genes based on hpo terms"""
    LOG.info("Running scout export hpo_genes")
    adapter = store

    header = ["#Gene_id\tCount"]

    if not hpo_term:
        LOG.warning("Please use at least one hpo term")
        raise click.Abort()

    for line in header:
        click.echo(line)

    for term in adapter.generate_hpo_gene_list(*hpo_term):
        click.echo("{0}\t{1}".format(term[0], term[1])) 
Example #14
Source File: panel.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def panel(panel, build, bed, version):
    """Export gene panels to .bed like format.

        Specify any number of panels on the command line
    """
    LOG.info("Running scout export panel")
    adapter = store

    # Save all chromosomes found in the collection if panels
    chromosomes_found = set()

    if not panel:
        LOG.warning("Please provide at least one gene panel")
        raise click.Abort()

    LOG.info("Exporting panels: {}".format(", ".join(panel)))
    if bed:
        if version:
            version = [version]
        lines = export_panels(adapter=adapter, panels=panel, versions=version, build=build)
    else:
        lines = export_gene_panels(adapter=adapter, panels=panel, version=version)
    for line in lines:
        click.echo(line) 
Example #15
Source File: policy.py    From anchore-cli with Apache License 2.0 6 votes vote down vote up
def describe(all=False, gate=None, trigger=None):
    ecode = 0
    try:
        ret = anchorecli.clients.apiexternal.describe_policy_spec(config)

        if ret['success']:
            render_payload = ret['payload']

            if not gate and not trigger:
                print(anchorecli.cli.utils.format_output(config, 'describe_gates', {'all': all}, render_payload))
            elif gate and not trigger:
                print(anchorecli.cli.utils.format_output(config, 'describe_gate_triggers', {'gate': gate, 'all': all}, render_payload))
            elif gate and trigger:
                print(anchorecli.cli.utils.format_output(config, 'describe_gate_trigger_params', {'gate': gate, 'trigger': trigger, 'all': all}, render_payload))
            else:
                raise click.Abort('Trigger can only be specified with --gate as well')
        else:
            raise Exception(json.dumps(ret['error'], indent=4))

    except Exception as err:
        print(anchorecli.cli.utils.format_error_output(config, 'describe_policy', {}, err))
        if not ecode:
            ecode = 2

    anchorecli.cli.utils.doexit(ecode) 
Example #16
Source File: compounds.py    From scout with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def compounds(case_id):
    """
    Update all compounds for a case
    """
    adapter = store
    LOG.info("Running scout update compounds")
    # Check if the case exists
    case_obj = adapter.case(case_id)

    if not case_obj:
        LOG.warning("Case %s could not be found", case_id)
        raise click.Abort()

    try:
        adapter.update_case_compounds(case_obj)
    except Exception as err:
        LOG.warning(err)
        raise click.Abort() 
Example #17
Source File: AccountCreator.py    From TensorHive with Apache License 2.0 6 votes vote down vote up
def _ask_for_username(self):
        '''
        Process is repeated until username becomes valid.
        If so, it assignes the vaule to the ORM object.
        '''
        valid_username_provided = False
        while not valid_username_provided:
            try:
                username = click.prompt('[1/4] UNIX username', type=str)
                self.new_user.username = username
            except click.Abort:
                raise
            except Exception as e:
                click.echo('Invalid username: {reason}.'.format(reason=e))
            else:
                valid_username_provided = True 
Example #18
Source File: cli.py    From csvtotable with MIT License 6 votes vote down vote up
def cli(*args, **kwargs):
    """
    CSVtoTable commandline utility.
    """
    # Convert CSV file
    content = convert.convert(kwargs["input_file"], **kwargs)

    # Serve the temporary file in browser.
    if kwargs["serve"]:
        convert.serve(content)
    # Write to output file
    elif kwargs["output_file"]:
        # Check if file can be overwrite
        if (not kwargs["overwrite"] and
                not prompt_overwrite(kwargs["output_file"])):
            raise click.Abort()

        convert.save(kwargs["output_file"], content)
        click.secho("File converted successfully: {}".format(
            kwargs["output_file"]), fg="green")
    else:
        # If its not server and output file is missing then raise error
        raise click.BadOptionUsage("Missing argument \"output_file\".") 
Example #19
Source File: cli.py    From lightflow with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def config_required(f):
    """ Decorator that checks whether a configuration file was set. """
    def new_func(obj, *args, **kwargs):
        if 'config' not in obj:
            click.echo(_style(obj.get('show_color', False),
                              'Could not find a valid configuration file!',
                              fg='red', bold=True))
            raise click.Abort()
        else:
            return f(obj, *args, **kwargs)
    return update_wrapper(new_func, f) 
Example #20
Source File: prompt_utils.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def prompt(*args, **kwargs):
    """Prompt the user for input and handle any abort exceptions."""
    try:
        return click.prompt(*args, **kwargs)
    except click.Abort:
        return False 
Example #21
Source File: wipe_database.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def abort_if_false(ctx, param, value):
    if not value:
        raise click.Abort() 
Example #22
Source File: panel.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _panel_omim(adapter, genemap2, mim2genes, api_key, institute, maintainer):
    """ Add OMIM panel to the database. """

    mim_files = None
    if genemap2 and mim2genes:
        mim_files = {
            "genemap2": list(get_file_handle(genemap2)),
            "mim2genes": list(get_file_handle(mim2genes)),
        }

    api_key = api_key or current_app.config.get("OMIM_API_KEY")
    if not api_key and mim_files is None:
        LOG.warning("Please provide a omim api key to load the omim gene panel")
        raise click.Abort()
    # Check if OMIM-AUTO exists
    if adapter.gene_panel(panel_id="OMIM-AUTO"):
        LOG.warning("OMIM-AUTO already exists in database")
        LOG.info("To create a new version use scout update omim")
        return

    if not mim_files:
        try:
            mim_files = fetch_mim_files(api_key=api_key, genemap2=True, mim2genes=True)
        except Exception as err:
            raise err

    # Here we know that there is no panel loaded
    try:
        adapter.load_omim_panel(
            genemap2_lines=mim_files["genemap2"],
            mim2gene_lines=mim_files["mim2genes"],
            institute=institute,
            maintainer=maintainer,
        )
    except Exception as err:
        LOG.error(err)
        raise click.Abort() 
Example #23
Source File: icloud.py    From ricloud with GNU Lesser General Public License v3.0 5 votes vote down vote up
def cmd_session_latest(source_identifier, user_identifier=None):
    user = helpers.get_or_create_user(user_identifier)

    sources = ricloud.Source.list(user=user, identifier=source_identifier)

    if sources.data:
        source = sources.data[0]
    else:
        warn(
            "No sources (identifier:{src_identifier}) found for user (identifier:{usr.identifier}).".format(
                src_identifier=source_identifier, usr=user
            )
        )
        raise click.Abort

    sessions = ricloud.Session.list(source=source, state="active", limit=1)

    if sessions.data:
        session = sessions.data[0]
    else:
        warn(
            "No active sessions exist for source (id:{src.id}, identifier:{src.identifier}).".format(
                src=source
            )
        )
        raise click.Abort

    info(compat.to_str(session)) 
Example #24
Source File: user.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def user(institute_id, user_name, user_mail, admin, user_id=None):
    """Add a user to the database."""
    adapter = store

    institutes = []
    for institute in institute_id:
        institute_obj = adapter.institute(institute_id=institute)

        if not institute_obj:
            LOG.warning("Institute % does not exist", institute)
            raise click.Abort()

        institutes.append(institute)

    roles = []
    if admin:
        LOG.info("User is admin")
        roles.append("admin")

    user_info = dict(
        email=user_mail.lower(), name=user_name, roles=roles, institutes=institutes, id=user_id,
    )

    user_obj = build_user(user_info)

    try:
        adapter.add_user(user_obj)
    except Exception as err:
        LOG.warning(err)
        raise click.Abort() 
Example #25
Source File: report.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def delivery_report(case_id, report_path, update):
    """Add delivery report to an existing case."""

    adapter = store

    try:
        load_delivery_report(
            adapter=adapter, case_id=case_id, report_path=report_path, update=update
        )
        LOG.info("saved report to case!")
    except Exception as err:
        LOG.error(err)
        raise click.Abort() 
Example #26
Source File: disease.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def diseases(api_key, genemap2):
    """
    Update disease terms in mongo database.

    If no file is specified the file will be fetched from OMIM with the api-key
    """
    adapter = store

    # Fetch the omim information
    api_key = api_key or current_app.config.get("OMIM_API_KEY")
    if genemap2:
        genemap_lines = get_file_handle(genemap2)

    else:
        if not api_key:
            LOG.warning("Please provide a omim api key to load the omim gene panel")
            raise click.Abort()

        try:
            mim_files = fetch_mim_files(api_key, genemap2=True)
            genemap_lines = mim_files["genemap2"]
        except Exception as err:
            LOG.warning(err)
            raise click.Abort()

    LOG.info("Dropping DiseaseTerms")
    adapter.disease_term_collection.drop()
    LOG.debug("DiseaseTerms dropped")
    load_disease_terms(adapter=adapter, genemap_lines=genemap_lines)

    LOG.info("Successfully loaded all disease terms") 
Example #27
Source File: icloud.py    From ricloud with GNU Lesser General Public License v3.0 5 votes vote down vote up
def cmd_poll_latest(session_id):
    polls = ricloud.Poll.list(session=session_id, limit=1)

    if polls.data:
        poll = polls.data[0]
    else:
        warn("No polls found for session (id:{})".format(session_id))
        raise click.Abort

    info(compat.to_str(poll)) 
Example #28
Source File: omim.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def omim(api_key, institute, genemap2, mim2genes):
    """
    Update the automate generated omim gene panel in the database.
    """
    LOG.info("Running scout update omim")
    adapter = store

    institute_obj = adapter.institute(institute)
    if not institute_obj:
        LOG.info("Institute %s could not be found in database", institute)
        LOG.warning("Please specify an existing institute")
        raise click.Abort()

    mim_files = None
    if genemap2 and mim2genes:
        mim_files = {
            "genemap2": list(get_file_handle(genemap2)),
            "mim2genes": list(get_file_handle(mim2genes)),
        }

    api_key = api_key or current_app.config.get("OMIM_API_KEY")
    if not api_key and mim_files is None:
        LOG.warning("Please provide a omim api key to load the omim gene panel")
        raise click.Abort()

    if not mim_files:
        try:
            mim_files = fetch_mim_files(api_key=api_key, genemap2=True, mim2genes=True)
        except Exception as err:
            raise err

    try:
        adapter.load_omim_panel(
            genemap2_lines=mim_files["genemap2"],
            mim2gene_lines=mim_files["mim2genes"],
            institute=institute,
        )
    except Exception as err:
        LOG.error(err)
        raise click.Abort() 
Example #29
Source File: helper_funcs.py    From hlsclt with MIT License 5 votes vote down vote up
def get_vars_from_file(filename):
    try:
        with click.open_file(filename) as f:
            config = imp.load_source('config', '', f)
        return config
    except (OSError, IOError):
        click.echo("Error: No hls_config.py found, please create a config file for your project. For an example config file please see the 'examples' folder within the hlsclt install directory.")
        raise click.Abort()

# Funtion to parse a loaded config structure and overwrite the config dictionary defaults. 
Example #30
Source File: serve.py    From scout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def serve(host, port, debug, livereload, test):
    """Start the web server."""
    pymongo_config = dict(
        MONGO_HOST=current_app.config.get("MONGO_HOST", "localhost"),
        MONGO_PORT=current_app.config.get("MONGO_PORT", 27017),
        MONGO_DBNAME=current_app.config.get("MONGO_DBNAME", "scout"),
        MONGO_USERNAME=current_app.config.get("MONGO_USERNAME", None),
        MONGO_PASSWORD=current_app.config.get("MONGO_PASSWORD", None),
    )

    valid_connection = check_connection(
        host=pymongo_config["MONGO_HOST"],
        port=pymongo_config["MONGO_PORT"],
        username=pymongo_config["MONGO_USERNAME"],
        password=pymongo_config["MONGO_PASSWORD"],
        authdb=current_app.config.get("MONGO_DBNAME", "scout"),
    )

    LOG.info("Test if mongod is running")
    if not valid_connection:
        LOG.warning("Connection could not be established")
        LOG.info("Is mongod running?")
        raise click.Abort()

    if test:
        LOG.info("Connection could be established")
        return

    if livereload:
        server = Server(current_app.wsgi_app)
        server.serve(host=host, port=port, debug=debug)
    else:
        return run_simple(
            hostname=host,
            port=port,
            application=current_app,
            use_reloader=False,
            use_debugger=debug,
        )