Python click.ClickException() Examples
The following are 30
code examples of click.ClickException().
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: adapter.py From django-click with MIT License | 8 votes |
def run_from_argv(self, argv): """ Called when run from the command line. """ prog_name = "{} {}".format(os.path.basename(argv[0]), argv[1]) try: # We won't get an exception here in standalone_mode=False exit_code = self.main( args=argv[2:], prog_name=prog_name, standalone_mode=False ) if exit_code: sys.exit(exit_code) except click.ClickException as e: if getattr(e.ctx, "traceback", False): # NOCOV raise e.show() sys.exit(e.exit_code)
Example #2
Source File: __init__.py From edgedb with Apache License 2.0 | 6 votes |
def restore(ctx, file: str, allow_nonempty: bool) -> None: cargs = ctx.obj['connargs'] conn = cargs.new_connection() dbname = conn.dbname try: if not is_empty_db(conn) and not allow_nonempty: raise click.ClickException( f'cannot restore into the {dbname!r} database: ' f'the database is not empty; ' f'consider using the --allow-nonempty option' ) restorer = restoremod.RestoreImpl() restorer.restore(conn, file) finally: conn.close()
Example #3
Source File: command_line.py From ivona-speak with MIT License | 6 votes |
def synthesize(access_key, secret_key, output_file, voice_name, voice_language, codec, text): """Synthesize passed text and save it as an audio file""" try: ivona_api = IvonaAPI( access_key, secret_key, voice_name=voice_name, language=voice_language, codec=codec, ) except (ValueError, IvonaAPIException) as e: raise click.ClickException("Something went wrong: {}".format(repr(e))) with click.open_file(output_file, 'wb') as file: ivona_api.text_to_speech(text, file) click.secho( "File successfully saved as '{}'".format(output_file), fg='green', )
Example #4
Source File: command_line.py From ivona-speak with MIT License | 6 votes |
def list_voices(access_key, secret_key, voice_language, voice_gender): """List available Ivona voices""" try: ivona_api = IvonaAPI(access_key, secret_key) except (ValueError, IvonaAPIException) as e: raise click.ClickException("Something went wrong: {}".format(repr(e))) click.echo("Listing available voices...") voices_list = ivona_api.get_available_voices( language=voice_language, gender=voice_gender, ) # Group voices by language voices_dict = dict() data = sorted(voices_list, key=lambda x: x['Language']) for k, g in groupby(data, key=lambda x: x['Language']): voices_dict[k] = list(g) for ln, voices in voices_dict.items(): voice_names = [v['Name'] for v in voices] click.echo("{}: {}".format(ln, ', '.join(voice_names))) click.secho("All done", fg='green')
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: common.py From xcube with MIT License | 6 votes |
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 #7
Source File: common.py From xcube with MIT License | 6 votes |
def parse_cli_kwargs(value: str, metavar: str = None) -> Dict[str, Any]: """ Parse a string value of the form [<kw>=<arg>{,<kw>=<arg>}] into a dictionary. <kw> must be a valid Python identifier, <arg> must be a Python literal. :param value: A string value. :param metavar: Name of a meta-variable used in CLI. :return: a dictionary of keyword-arguments """ if value: try: return eval(f"dict({value})", {}, {}) except Exception: if metavar: message = f"Invalid value for {metavar}: {value!r}" else: message = f"Invalid value: {value!r}" raise click.ClickException(message) else: return dict()
Example #8
Source File: prune.py From xcube with MIT License | 6 votes |
def _prune(input_path: str = None, dry_run: bool = False, monitor=None): from xcube.core.chunk import get_empty_dataset_chunks from xcube.core.dsio import guess_dataset_format from xcube.core.dsio import open_cube input_format = guess_dataset_format(input_path) if input_format != FORMAT_NAME_ZARR: raise click.ClickException("input must be a cube in ZARR format") monitor(f'Opening cube from {input_path!r}...') with open_cube(input_path) as cube: monitor('Identifying empty blocks...') empty_chunks = get_empty_dataset_chunks(cube) num_deleted = 0 for var_name, chunk_indices in empty_chunks.items(): monitor(f'Deleting {len(chunk_indices)} empty block file(s) for variable {var_name!r}...') for chunk_index in chunk_indices: ok = _delete_block_file(input_path, var_name, chunk_index, dry_run, monitor) if ok: num_deleted += 1 monitor(f'Done, {num_deleted} block file(s) deleted.')
Example #9
Source File: filters.py From yasha with MIT License | 6 votes |
def do_subprocess(cmd, stdout=True, stderr=True, check=True, timeout=2): assert sys.version_info >= (3,5) kwargs = dict( stdout=subprocess.PIPE if stdout else None, stderr=subprocess.PIPE if stderr else None, shell=True, check=False, timeout=timeout, ) try: result = subprocess.run(cmd, **kwargs) except subprocess.TimeoutExpired: msg = "Command '{}' timed out after waiting for {} seconds" raise ClickException(msg.format(cmd, timeout)) if check and result.returncode: errno = result.returncode error = result.stderr.decode().strip() msg = "Command '{}' returned non-zero exit status {}\n{}" raise ClickException(msg.format(cmd, errno, error)) return result
Example #10
Source File: test_common.py From xcube with MIT License | 6 votes |
def test_parse_cli_kwargs(self): self.assertEqual(dict(), parse_cli_kwargs("", metavar="<chunks>")) self.assertEqual(dict(time=1, lat=256, lon=512), parse_cli_kwargs("time=1, lat=256, lon=512", metavar="<chunks>")) self.assertEqual(dict(chl_conc=(0, 20, 'greens'), chl_tsm=(0, 15, 'viridis')), parse_cli_kwargs("chl_conc=(0,20,'greens'),chl_tsm=(0,15,'viridis')", metavar="<styles>")) with self.assertRaises(click.ClickException) as cm: parse_cli_kwargs("45 * 'A'", metavar="<chunks>") self.assertEqual("Invalid value for <chunks>: \"45 * 'A'\"", f"{cm.exception}") with self.assertRaises(click.ClickException) as cm: parse_cli_kwargs("9==2") self.assertEqual("Invalid value: '9==2'", f"{cm.exception}")
Example #11
Source File: cli.py From flex with MIT License | 6 votes |
def main(source): """ For a given command line supplied argument, negotiate the content, parse the schema and then return any issues to stdout or if no schema issues, return success exit code. """ if source is None: click.echo( "You need to supply a file or url to a schema to a swagger schema, for" "the validator to work." ) return 1 try: load(source) click.echo("Validation passed") return 0 except ValidationError as e: raise click.ClickException(str(e))
Example #12
Source File: cli.py From butterknife with MIT License | 6 votes |
def verify(subvol, manifest): if os.getuid(): raise click.ClickException("Run as root or use sudo") if not manifest: manifest = "/var/lib/butterknife/manifests/%s" % subvol if not subvol: raise click.ClickException("Failed to determine template corresponding to root filesystem, try specifying particular template to verify") click.echo("Verifying %s" % subvol) if subvol.endswith("/"): subvol = subvol[:-1] if not subvol.startswith("/"): subvol = os.path.join("/var/lib/butterknife/pool", subvol) verify_manifest(subvol) # This will raise exceptions click.echo("Verification successful")
Example #13
Source File: __init__.py From lokey with GNU General Public License v3.0 | 6 votes |
def cli(ctx, password): if not hasattr(ctx.obj, 'key'): ctx.obj = LokeyContext() interactive_terminal = sys.__stdin__.isatty() subcommand = ctx.invoked_subcommand if interactive_terminal and not subcommand: print("\n".join([ ctx.get_help(), "", "Examples:", " $ cat your-key | lokey to ssh", " $ lokey fetch keybase twitter:jf", ""])) return elif interactive_terminal and subcommand: return try: ctx.obj.key = eris.load(sys.stdin, password=password) except Exception as e: raise click.ClickException(str(e)) if not subcommand: print ctx.obj.key
Example #14
Source File: build.py From travis-sphinx with GNU General Public License v3.0 | 6 votes |
def build(ctx, source, nowarn): """ Build documentation from ``source``, placing built files in ``target``. """ _logger.info('building documentation') outdir = ctx.obj['outdir'] if sphinx_version_at_least_1_7: # args have to be specified this way for 1.7+, otherwise one gets # "Builder name html not registered or available through entry point" # See https://github.com/sphinx-doc/sphinx/issues/4623 args = ['-b', 'html'] else: args = ['-b html'] if not nowarn: args.append('-W') if build_main(args + [source, outdir]): raise click.ClickException("Error building sphinx doc")
Example #15
Source File: templates.py From python-viptela with GNU General Public License v3.0 | 6 votes |
def templates(ctx, template_type, name, export_file): """ Export templates to file """ vmanage_files = Files(ctx.auth, ctx.host) if template_type == 'device': if name: click.echo(f'Exporting device template(s) {",".join(name)} to {export_file}') vmanage_files.export_templates_to_file(export_file, name_list=name, template_type='device') else: click.echo(f'Exporting device templates to {export_file}') vmanage_files.export_templates_to_file(export_file, template_type='device') elif template_type == 'feature': if name: click.echo(f'Exporting feature template(s) {",".join(name)} to {export_file}') vmanage_files.export_templates_to_file(export_file, name_list=name, template_type='feature') else: click.echo(f'Exporting feature templates to {export_file}') vmanage_files.export_templates_to_file(export_file, template_type='feature') else: if name: raise click.ClickException("Must specify template type with name") click.echo(f'Exporting templates to {export_file}') vmanage_files.export_templates_to_file(export_file)
Example #16
Source File: cli.py From certidude with MIT License | 6 votes |
def certidude_housekeeping_kinit(): from certidude import config # Update LDAP service ticket if Certidude is joined to domain if not os.path.exists("/etc/krb5.keytab"): raise click.ClickException("No Kerberos keytab configured") _, kdc = config.LDAP_ACCOUNTS_URI.rsplit("/", 1) cmd = "KRB5CCNAME=%s.part kinit -k %s$ -S ldap/%s@%s -t /etc/krb5.keytab" % ( config.LDAP_GSSAPI_CRED_CACHE, const.HOSTNAME.upper(), kdc, config.KERBEROS_REALM ) click.echo("Executing: %s" % cmd) if os.system(cmd): raise click.ClickException("Failed to initialize Kerberos credential cache!") os.system("chown certidude:certidude %s.part" % config.LDAP_GSSAPI_CRED_CACHE) os.rename("%s.part" % config.LDAP_GSSAPI_CRED_CACHE, config.LDAP_GSSAPI_CRED_CACHE)
Example #17
Source File: devicetool.py From assistant-sdk-python with Apache License 2.0 | 6 votes |
def cli(ctx, project_id, verbose, api_endpoint, credentials): try: with open(credentials, 'r') as f: c = google.oauth2.credentials.Credentials(token=None, **json.load(f)) http_request = google.auth.transport.requests.Request() c.refresh(http_request) except Exception as e: raise click.ClickException('Error loading credentials: %s.\n' 'Run google-oauthlib-tool to initialize ' 'new OAuth 2.0 credentials.' % e) ctx.obj['API_ENDPOINT'] = api_endpoint ctx.obj['API_VERSION'] = ASSISTANT_API_VERSION ctx.obj['SESSION'] = None ctx.obj['PROJECT_ID'] = project_id ctx.obj['CREDENTIALS'] = c if verbose: logging.getLogger().setLevel(logging.DEBUG)
Example #18
Source File: datamgr.py From ibis with Apache License 2.0 | 6 votes |
def parquet(tables, data_directory, ignore_missing_dependency, **params): try: import pyarrow as pa # noqa: F401 import pyarrow.parquet as pq # noqa: F401 except ImportError: msg = 'PyArrow dependency is missing' if ignore_missing_dependency: logger.warning('Ignored: %s', msg) return 0 else: raise click.ClickException(msg) data_directory = Path(data_directory) for table, df in read_tables(tables, data_directory): arrow_table = pa.Table.from_pandas(df) target_path = data_directory / '{}.parquet'.format(table) pq.write_table(arrow_table, str(target_path))
Example #19
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 #20
Source File: compute.py From xcube with MIT License | 5 votes |
def _get_function(object, function_name, source, force=False): function = object.get(function_name) if function is None: if force: raise click.ClickException(f"missing function {function_name!r} in {source}") else: return None if not callable(function): raise click.ClickException(f"{function_name!r} in {source} is not a callable") return function
Example #21
Source File: maintenance.py From ms_deisotope with Apache License 2.0 | 5 votes |
def register_thermo_com_net(path): '''Register a bundle of Thermo's RawFileReader library's DLLs. The `--path` option can be used to specify additional search paths. ''' if path is None: path = [] try: import clr except ImportError: click.secho("pythonnet not installed", fg='yellow') raise click.ClickException( "This feature requires the pythonnet library. Please install it.") from ms_deisotope.data_source.thermo_raw_net import _register_dll, _RawFileReader from ms_deisotope.data_source.thermo_raw_net import determine_if_available if _RawFileReader: click.secho("DLL Already Registered and Loaded") return result = _register_dll(path) if result: click.secho("DLL Registration Successful") if determine_if_available(): click.secho("DLL Load Succesful", fg='cyan') if path is not None: config = get_config() rest = sorted(set(path) - set(config['vendor_readers']['thermo-net'])) config['vendor_readers']['thermo-net'].extend(rest) save_config(config) else: click.secho("DLL Load Unsuccessful", fg='red') else: click.secho("DLL Registration Unsuccessful")
Example #22
Source File: maintenance.py From ms_deisotope with Apache License 2.0 | 5 votes |
def register_thermo_com(path=None): '''Register an installed MSFileReader or XRawFile DLL. Searches the standard installation paths, but the `--path` option can be used to specify additional search paths. ''' if path is None: path = [] try: import comtypes except ImportError: click.secho("comtypes not installed", fg='yellow') raise click.ClickException( "This feature requires the comtypes library. Please install it.") import logging from ms_deisotope.data_source._vendor.MSFileReader import _register_dll, log, DLL_IS_LOADED from ms_deisotope.data_source.thermo_raw import determine_if_available if DLL_IS_LOADED: click.secho("DLL Already Registered and Loaded") return if log is not None: log.addHandler(logging.StreamHandler()) log.setLevel('DEBUG') result = _register_dll(path) if result: click.secho("DLL Registration Successful") if determine_if_available(): click.secho("DLL Load Succesful", fg='cyan') if path is not None: config = get_config() config['vendor_readers']['thermo-com'].extend(path) save_config(config) else: click.secho("DLL Load Unsuccessful", fg='red') else: click.secho("DLL Registration Unsuccessful") if log is not None: log.handlers = log.handlers[:-1]
Example #23
Source File: utils.py From openag_python with GNU General Public License v3.0 | 5 votes |
def check_for_cloud_user(): """ Raise an error if the user is not logged into their cloud server. Assumes there is a cloud server (i.e. check_for_cloud_server would succeed) """ if not config["cloud_server"]["username"]: raise ClickException( "Not logged into cloud server. Run `openag cloud register` to " "create a user account or `openag cloud login` to log in with an " "existing account" )
Example #24
Source File: devicetool.py From assistant-sdk-python with Apache License 2.0 | 5 votes |
def failed_request_exception(message, r): """Build ClickException from a failed request.""" try: resp = json.loads(r.text) message = '%s: %d\n%s' % (message, resp['error']['code'], resp['error']['message']) return click.ClickException(message) except ValueError: # fallback on raw text response if error is not structured. return click.ClickException('%s: %d\n%s' % (message, r.status_code, r.text))
Example #25
Source File: cli.py From chinese-support-redux with GNU General Public License v3.0 | 5 votes |
def tts_cli(text, file, output, slow, lang, nocheck): """ Read <text> to mp3 format using Google Translate's Text-to-Speech API (set <text> or --file <file> to - for standard input) """ # stdin for <text> if text == '-': text = click.get_text_stream('stdin').read() # stdout (when no <output>) if not output: output = click.get_binary_stream('stdout') # <file> input (stdin on '-' is handled by click.File) if file: try: text = file.read() except UnicodeDecodeError as e: # pragma: no cover log.debug(str(e), exc_info=True) raise click.FileError( file.name, "<file> must be encoded using '%s'." % sys_encoding()) # TTS try: tts = gTTS( text=text, lang=lang, slow=slow, lang_check=not nocheck) tts.write_to_fp(output) except (ValueError, AssertionError) as e: raise click.UsageError(str(e)) except gTTSError as e: raise click.ClickException(str(e))
Example #26
Source File: cli.py From chinese-support-redux with GNU General Public License v3.0 | 5 votes |
def print_languages(ctx, param, value): """Callback for <all> flag. Prints formatted sorted list of supported languages and exits """ if not value or ctx.resilient_parsing: return try: langs = tts_langs() langs_str_list = sorted("{}: {}".format(k, langs[k]) for k in langs) click.echo(' ' + '\n '.join(langs_str_list)) except RuntimeError as e: # pragma: no cover log.debug(str(e), exc_info=True) raise click.ClickException("Couldn't fetch language list.") ctx.exit()
Example #27
Source File: utils.py From openag_python with GNU General Public License v3.0 | 5 votes |
def check_for_cloud_farm(): """ Raise an error if no farm is selected on the cloud server. Assumes there is a cloud server (i.e. check_for_cloud_server would succeed) """ if not config["cloud_server"]["farm_name"]: raise ClickException( "No farm selected. Run `openag cloud farm create` to create a " "farm, `openag cloud farm list` to see what farms you have access " "to, and `openag cloud farm select` to select a farm" )
Example #28
Source File: __main__.py From pylivetrader with Apache License 2.0 | 5 votes |
def migrate(**kwargs): try: click.echo("make sure source file is python 3 compatible") click.echo( migration_tool.make_sure_source_code_is_python3_compatible( kwargs["in_file"]) ) data = open(kwargs["in_file"], "r").read() emulate_progress_bar("check for unsupported modules", 5) migration_tool.check_for_unsupported_modules(data) emulate_progress_bar("make sure all required methods are implemented") data = migration_tool.add_missing_base_methods(data) emulate_progress_bar("remove unsupported imports", 5) data = migration_tool.remove_quantopian_imports(data) data = migration_tool.remove_commission(data) emulate_progress_bar("define a logger", 5) data = migration_tool.define_logger(data) emulate_progress_bar("checking if using pipeline", 5) data = migration_tool.add_pipelinelive_imports(data) emulate_progress_bar("adding pylivetrader imports", 5) data = migration_tool.add_pylivetrader_imports(data) emulate_progress_bar("Finalizing") data = migration_tool.cleanup(data) with open(kwargs["out_file"], 'w') as f: f.write(data) except Exception as e: raise ClickException(e)
Example #29
Source File: mng.py From edgedb with Apache License 2.0 | 5 votes |
def drop_role(ctx, role_name, **kwargs): utils.connect(ctx) qry = f''' DROP ROLE {qi(role_name)}; ''' try: ctx.obj['conn'].execute(qry) except edgedb.EdgeDBError as e: raise click.ClickException(str(e)) from e
Example #30
Source File: mng.py From edgedb with Apache License 2.0 | 5 votes |
def alter_role(ctx, role_name, **kwargs): utils.connect(ctx) attrs = ";\n".join(_process_role_options(ctx, **kwargs)) qry = f''' ALTER ROLE {qi(role_name)} {{ {attrs} }} ''' try: ctx.obj['conn'].execute(qry) except edgedb.EdgeDBError as e: raise click.ClickException(str(e)) from e