Python click.BadParameter() Examples
The following are 30
code examples of click.BadParameter().
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: test_nelson_siegel_svensson.py From nelson_siegel_svensson with MIT License | 6 votes |
def test_float_array_parameters(self): '''Test float array parameter.''' param = cli.FloatArray() self.assertRaises(click.BadParameter, param.convert, value='', param=None, ctx=None) self.assertRaises(click.BadParameter, param.convert, value='{"a": 1}', param=None, ctx=None) self.assertRaises(click.BadParameter, param.convert, value='["a"]', param=None, ctx=None) self.assertEqual(np.array([1.0]), param.convert('[1.0]', None, None)) self.assertEqual(np.array([1.0]), param.convert('[1]', None, None)) self.assertEqual([], param.convert('[]', None, None).tolist()) self.assertTrue((np.array([1.0, 2.0, 3.0]) == param.convert('[1, 2,3.0]', None, None)).all())
Example #2
Source File: dataset.py From renku-python with Apache License 2.0 | 6 votes |
def export_( short_name, provider, publish, tag, dataverse_server, dataverse_name ): """Export data to 3rd party provider.""" try: output = export_dataset( short_name=short_name, provider=provider, publish=publish, tag=tag, handle_access_token_fn=prompt_access_token, handle_tag_selection_fn=prompt_tag_selection, dataverse_server_url=dataverse_server, dataverse_name=dataverse_name, ) except ( ValueError, InvalidAccessToken, DatasetNotFound, requests.HTTPError ) as e: raise click.BadParameter(e) click.echo(output) click.secho('OK', fg='green')
Example #3
Source File: test_nelson_siegel_svensson.py From nelson_siegel_svensson with MIT License | 6 votes |
def test_curve_parameters(self): '''Test curve parameter.''' param = cli.Curve() self.assertRaises(click.BadParameter, param.convert, value='', param=None, ctx=None) self.assertRaises(click.BadParameter, param.convert, value='{}', param=None, ctx=None) missing_tau = '{"beta0": 0.017, "beta1": -0.023, "beta2": 0.24}' self.assertRaises(click.BadParameter, param.convert, value=missing_tau, param=None, ctx=None) self.assertEqual(self.y1, param.convert(json.dumps(asdict(self.y1)), None, None)) self.assertEqual(self.y2, param.convert(json.dumps(asdict(self.y2)), None, None))
Example #4
Source File: db.py From openag_python with GNU General Public License v3.0 | 6 votes |
def init(cloud_url): """ Choose a cloud server to use. Sets CLOUD_URL as the cloud server to use and sets up replication of global databases from that cloud server if a local database is already initialized (via `openag db init`). """ old_cloud_url = config["cloud_server"]["url"] if old_cloud_url and old_cloud_url != cloud_url: raise click.ClickException( 'Server "{}" already selected. Call `openag cloud deinit` to ' 'detach from that server before selecting a new one'.format( old_cloud_url ) ) parsed_url = urlparse(cloud_url) if not parsed_url.scheme or not parsed_url.netloc or not parsed_url.port: raise click.BadParameter("Invalid url") if config["local_server"]["url"]: utils.replicate_global_dbs(cloud_url=cloud_url) config["cloud_server"]["url"] = cloud_url
Example #5
Source File: options.py From yatsm with MIT License | 6 votes |
def arg_date(var='date', metavar='<date>', date_frmt_key='date_frmt'): def _arg_date(f): def callback(ctx, param, value): try: value = dt.strptime(value, ctx.params[date_frmt_key]) except KeyError: raise click.ClickException( 'Need to use `date_format_opt` when using `date_arg`') except ValueError: raise click.BadParameter( 'Cannot parse {v} to date with format {f}'.format( v=value, f=ctx.params['date_frmt'])) else: return value return click.argument(var, metavar=metavar, callback=callback)(f) return _arg_date
Example #6
Source File: options.py From yatsm with MIT License | 6 votes |
def valid_int_gt_zero(ctx, param, value): """ Validator for integers > 0 (value >= 1)""" def _validator(param, value): try: value = int(value) except Exception as e: raise click.BadParameter('%s must be integer above zero: %s' % (param.metavar, e.message)) if value <= 0: raise click.BadParameter('%s must be an integer above zero' % param.metavar) return value if param.multiple: return [_validator(param, v) for v in value] else: return _validator(param, value) # CLI ARGUMENTS
Example #7
Source File: options.py From yatsm with MIT License | 6 votes |
def arg_job_number(f): def callback(ctx, param, value): try: value = int(value) except: raise click.BadParameter('Must specify an integer >= 0') if value < 0: raise click.BadParameter('Must specify an integer >= 0') elif value == 0: return value else: return value - 1 return click.argument('job_number', nargs=1, callback=callback, metavar='<job_number>')(f) # CLI OPTIONS
Example #8
Source File: options.py From yatsm with MIT License | 6 votes |
def opt_exampleimg(f): def callback(ctx, param, value): # Check if file qualifies alone if os.path.isfile(value): _value = value else: # Check if path relative to root qualifies _value = os.path.join(ctx.params['root'], value) if not os.path.isfile(_value): raise click.BadParameter('Cannot find example image ' '"{f}"'.format(f=value)) if not os.access(_value, os.R_OK): raise click.BadParameter('Found example image but cannot ' 'read from "{f}"'.format(f=_value)) return os.path.abspath(_value) return click.option('--image', '-i', default='example_img', metavar='<image>', show_default=True, help='Example timeseries image', callback=callback)(f)
Example #9
Source File: options.py From yatsm with MIT License | 6 votes |
def opt_resultdir(f): def callback(ctx, param, value): # Check if path qualifies alone if os.path.isdir(value): _value = value else: # Check if path relative to root qualifies _value = os.path.join(ctx.params['root'], value) if not os.path.isdir(_value): raise click.BadParameter('Cannot find result directory ' '"{d}"'.format(d=value)) if not os.access(_value, os.R_OK): raise click.BadParameter('Found result directory but cannot ' 'read from "{d}"'.format(d=_value)) return os.path.abspath(_value) return click.option('--result', '-r', default='YATSM', metavar='<directory>', show_default=True, help='Directory of results', callback=callback)(f) # CALLBACKS
Example #10
Source File: callbacks.py From schemathesis with MIT License | 6 votes |
def validate_headers( ctx: click.core.Context, param: click.core.Parameter, raw_value: Tuple[str, ...] ) -> Dict[str, str]: headers = {} for header in raw_value: with reraise_format_error(header): key, value = header.split(":", maxsplit=1) value = value.lstrip() key = key.strip() if not key: raise click.BadParameter("Header name should not be empty") if not utils.is_latin_1_encodable(key): raise click.BadParameter("Header name should be latin-1 encodable") if not utils.is_latin_1_encodable(value): raise click.BadParameter("Header value should be latin-1 encodable") if utils.has_invalid_characters(key, value): raise click.BadParameter("Invalid return character or leading space in header") headers[key] = value return headers
Example #11
Source File: commands.py From sphinx-intl with BSD 2-Clause "Simplified" License | 6 votes |
def read_config(path, passed_tags): tags = Tags() passed_tags = sum(passed_tags, ()) for tag in passed_tags: tags.add(tag) namespace = { "__file__": os.path.abspath(path), "tags": tags, } olddir = os.getcwd() try: if not os.path.isfile(path): msg = "'%s' is not found (or specify --locale-dir option)." % path raise click.BadParameter(msg) os.chdir(os.path.dirname(path) or ".") execfile_(os.path.basename(path), namespace) finally: os.chdir(olddir) return namespace
Example #12
Source File: transifex.py From sphinx-intl with BSD 2-Clause "Simplified" License | 6 votes |
def create_transifexrc(transifex_username, transifex_password): """ Create `$HOME/.transifexrc` """ target = os.path.normpath(os.path.expanduser('~/.transifexrc')) if os.path.exists(target): click.echo('{0} already exists, skipped.'.format(target)) return if not transifex_username or not 'transifex_password': msg = textwrap.dedent("""\ You need transifex username/password by command option or environment. command option: --transifex-username, --transifex-password """) raise click.BadParameter(msg, param_hint='transifex_username,transifex_password') with open(target, 'wt') as rc: rc.write(TRANSIFEXRC_TEMPLATE % locals()) click.echo('Create: {0}'.format(target))
Example #13
Source File: utils.py From isitfit with Apache License 2.0 | 6 votes |
def validate_profile(self, ctx, param, value_colored): if value_colored is None: return value_colored value_nocolor = decolorize(value_colored) # check if in list if value_nocolor not in self.profile_list_nocolors: import click err_m = 'Profile "%s" (decolored to "%s") is not from ~/.aws/credentials file.'%(value_colored, value_nocolor) raise click.BadParameter(err_m) # set the profile in an env var so that boto3 picks it up automatically if value_nocolor is not None: import os os.environ['AWS_PROFILE'] = value_nocolor # save profile in click context for other usage in displayed/emailed report ctx.obj['aws_profile'] = value_nocolor # save in last-used profile file self.last_profile_cls.set(value_nocolor) # done return value_nocolor
Example #14
Source File: helpers.py From zap-cli with MIT License | 6 votes |
def validate_scanner_list(ctx, param, value): """ Validate a comma-separated list of scanners and extract it into a list of groups and IDs. """ if not value: return None valid_groups = ctx.obj.scanner_groups scanners = [x.strip() for x in value.split(',')] if 'all' in scanners: return ['all'] scanner_ids = [] for scanner in scanners: if scanner.isdigit(): scanner_ids.append(scanner) elif scanner in valid_groups: scanner_ids += ctx.obj.scanner_group_map[scanner] else: raise click.BadParameter('Invalid scanner "{0}" provided. Must be a valid group or numeric ID.' .format(scanner)) return scanner_ids
Example #15
Source File: finam-lookup.py From finam-export with Apache License 2.0 | 6 votes |
def main(contract, market): exporter = Exporter() if all((contract, market)): raise click.BadParameter('Either contract or market must be specified') elif not any((contract, market)): raise click.BadParameter('Neither contract nor market is specified') pd.options.display.max_rows = 1000 if contract: try: meta = exporter.lookup(code=contract) except FinamObjectNotFoundError: logger.info('No such contract') else: print(meta) else: contracts = exporter.lookup(market=Market[market]) print(contracts)
Example #16
Source File: click.py From pathvalidate with MIT License | 5 votes |
def filepath(ctx, param, value): # pragma: no cover # Deprecated if not value: return None try: validate_filepath(value) except ValidationError as e: raise click.BadParameter(str(e)) return sanitize_filepath(value)
Example #17
Source File: conductor.py From pros-cli2 with Mozilla Public License 2.0 | 5 votes |
def remove_depot(cfg, name): if name == 'pros-mainline': raise click.BadParameter('Cannot delete pros-mainline!') for depot in [d for d in utils.get_depot_configs(cfg.pros_cfg) if d.name == name]: click.echo('Removing {} ({})'.format(depot.name, depot.location)) depot.delete()
Example #18
Source File: helpers.py From zap-cli with MIT License | 5 votes |
def validate_regex(ctx, param, value): """ Validate that a provided regex compiles. """ if not value: return None try: re.compile(value) except re.error: raise click.BadParameter('Invalid regex "{0}" provided'.format(value)) return value
Example #19
Source File: helpers.py From zap-cli with MIT License | 5 votes |
def validate_ids(ctx, param, value): """Validate a list of IDs and convert them to a list.""" if not value: return None ids = [x.strip() for x in value.split(',')] for id_item in ids: if not id_item.isdigit(): raise click.BadParameter('Non-numeric value "{0}" provided for an ID.'.format(id_item)) return ids
Example #20
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 #21
Source File: command_line.py From Dallinger with MIT License | 5 votes |
def qualify(workers, qualification, value, by_name, notify, sandbox): """Assign a qualification to 1 or more workers""" if not (workers and qualification and value): raise click.BadParameter( "Must specify a qualification ID, value/score, 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 click.echo( "Assigning qualification {} with value {} to {} worker{}...".format( qid, value, len(workers), "s" if len(workers) > 1 else "" ) ) for worker in workers: if mturk.assign_qualification(qid, worker, int(value), notify=notify): click.echo("{} OK".format(worker)) # print out the current set of workers with the qualification results = list(mturk.get_workers_with_qualification(qid)) click.echo("{} workers with qualification {}:".format(len(results), qid)) for score, count in Counter([r["score"] for r in results]).items(): click.echo("{} with value {}".format(count, score))
Example #22
Source File: app.py From pyethapp with BSD 3-Clause "New" or "Revised" License | 5 votes |
def app(ctx, alt_config, config_values, data_dir, log_config, bootstrap_node, log_json, mining_pct): # configure logging log_config = log_config or ':info' slogging.configure(log_config, log_json=log_json) # data dir default or from cli option data_dir = data_dir or konfig.default_data_dir konfig.setup_data_dir(data_dir) # if not available, sets up data_dir and required config log.info('using data in', path=data_dir) # prepare configuration # config files only contain required config (privkeys) and config different from the default if alt_config: # specified config file config = konfig.load_config(alt_config) else: # load config from default or set data_dir config = konfig.load_config(data_dir) config['data_dir'] = data_dir # add default config konfig.update_config_with_defaults(config, konfig.get_default_config([EthApp] + services)) # override values with values from cmd line for config_value in config_values: try: konfig.set_config_param(config, config_value) # check if this is part of the default config except ValueError: raise BadParameter('Config parameter must be of the form "a.b.c=d" where "a.b.c" ' 'specifies the parameter to set and d is a valid yaml value ' '(example: "-c jsonrpc.port=5000")') if bootstrap_node: config['discovery']['bootstrap_nodes'] = [bytes(bootstrap_node)] if mining_pct > 0: config['pow']['activated'] = True config['pow']['cpu_pct'] = int(min(100, mining_pct)) ctx.obj = {'config': config}
Example #23
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def validate_prompt_hostname(hostname): if hostname == '' or utils.is_valid_hostname(hostname): return hostname raise click.BadParameter('Invalid hostname. Please double-check this value and re-enter it.')
Example #24
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def validate_ansible_dir(path): if not path: raise click.BadParameter('An Ansible path must be provided') return path # if not os.path.exists(path)): # raise click.BadParameter("Path \"{}\" doesn't exist".format(path))
Example #25
Source File: run_benchmarks.py From garage with MIT License | 5 votes |
def run(names): """Run selected benchmarks. Args: names (tuple): Benchmark names. Raises: BadParameter: if any run name is invalid or duplicated. """ if not names: raise click.BadParameter('Empty names!') if len(names) != len(set(names)): raise click.BadParameter('Duplicate names!') options = _get_all_options() for name in names: if name not in options: raise click.BadParameter( 'Invalid run name! Make sure every name can be found in ' '`garage_benchmark list`!') for name in names: options[name]()
Example #26
Source File: helper.py From twtxt with MIT License | 5 votes |
def validate_created_at(ctx, param, value): if value: try: return parse_iso8601(value) except (ValueError, OverflowError) as e: raise click.BadParameter("{0}.".format(e))
Example #27
Source File: finam-download.py From finam-export with Apache License 2.0 | 5 votes |
def _arg_split(ctx, param, value): if value is None: return value try: items = value.split(',') except ValueError: raise click.BadParameter('comma-separated {} is required, got {}' .format(param, value)) return items
Example #28
Source File: ci.py From web2board with GNU Lesser General Public License v3.0 | 5 votes |
def cli(ctx, src, lib, exclude, board, # pylint: disable=R0913 build_dir, keep_build_dir, project_conf, verbose): if not src: src = getenv("PLATFORMIO_CI_SRC", "").split(":") if not src: raise click.BadParameter("Missing argument 'src'") try: app.set_session_var("force_option", True) _clean_dir(build_dir) for dir_name, patterns in dict(lib=lib, src=src).iteritems(): if not patterns: continue contents = [] for p in patterns: contents += glob(p) _copy_contents(join(build_dir, dir_name), contents) if project_conf and isfile(project_conf): copyfile(project_conf, join(build_dir, "platformio.ini")) elif not board: raise CIBuildEnvsEmpty() if exclude: _exclude_contents(build_dir, exclude) # initialise project ctx.invoke(cmd_init, project_dir=build_dir, board=board) # process project ctx.invoke(cmd_run, project_dir=build_dir, verbose=verbose) finally: if not keep_build_dir: rmtree( build_dir, onerror=lambda action, name, exc: (chmod(name, stat.S_IWRITE), remove(name)) )
Example #29
Source File: ci.py From web2board with GNU Lesser General Public License v3.0 | 5 votes |
def validate_boards(ctx, param, value): # pylint: disable=W0613 unknown_boards = set(value) - set(get_boards().keys()) try: assert not unknown_boards return value except AssertionError: raise click.BadParameter( "%s. Please search for the board types using " "`platformio boards` command" % ", ".join(unknown_boards))
Example #30
Source File: ci.py From web2board with GNU Lesser General Public License v3.0 | 5 votes |
def validate_path(ctx, param, value): # pylint: disable=W0613 invalid_path = None value = list(value) for i, p in enumerate(value): if p.startswith("~"): value[i] = expanduser(p) value[i] = abspath(value[i]) if not glob(value[i]): invalid_path = p break try: assert invalid_path is None return value except AssertionError: raise click.BadParameter("Found invalid path: %s" % invalid_path)