我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用click.echo()。
def delete(experiment, project): """Delete experiment group.""" user, project_name = get_project_or_local(project) if not click.confirm("Are sure you want to delete experiment `{}`".format(experiment)): click.echo('Existing without deleting experiment.') sys.exit(1) try: response = PolyaxonClients().experiment.delete_experiment( user, project_name, experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError) as e: Printer.print_error('Could not delete experiment `{}`.'.format(experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Experiment `{}` was delete successfully".format(experiment))
def stop(experiment, project): """Get experiment by uuid. Examples:
polyaxon experiment stop 2 ``` """ user, project_name = get_project_or_local(project) if not click.confirm("Are sure you want to stop experiment `{}`".format(experiment)): click.echo('Existing without stopping experiment.') sys.exit(0) try: PolyaxonClients().experiment.stop(user, project_name, experiment) except (PolyaxonHTTPError, PolyaxonShouldExitError) as e: Printer.print_error('Could not stop experiment `{}`.'.format(experiment)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) Printer.print_success("Experiment is being stopped.")
```
def delete(project): """Delete project.""" user, project_name = get_project_or_local(project) if not click.confirm("Are sure you want to delete project `{}/{}`".format(user, project_name)): click.echo('Existing without deleting project.') sys.exit(1) try: response = PolyaxonClients().project.delete_project(user, project_name) except (PolyaxonHTTPError, PolyaxonShouldExitError) as e: Printer.print_error('Could not delete project `{}`.'.format(project)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Project `{}` was delete successfully".format(project))
def delete(group, project): """Delete experiment group.""" user, project_name = get_project_or_local(project) if not click.confirm("Are sure you want to delete experiment group `{}`".format(group)): click.echo('Existing without deleting experiment group.') sys.exit(0) try: response = PolyaxonClients().experiment_group.delete_experiment_group( user, project_name, group) except (PolyaxonHTTPError, PolyaxonShouldExitError) as e: Printer.print_error('Could not delete experiment group `{}`.'.format(group)) Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) if response.status_code == 204: Printer.print_success("Experiment group `{}` was delete successfully".format(group))
def get(keys): """Get global config values by keys. Example:
polyaxon config get host http_port ``` """ config = GlobalConfigManager.get_config() or GlobalConfigManager.CONFIG() if len(keys) == 0: return print_values = {} for key in keys: if hasattr(config, key): print_values[key] = getattr(config, key) else: click.echo('Key `{}` is not recognised.'.format(key)) dict_tabulate(print_values, )
def resources(cls, jobs_resources): jobs_resources = to_list(jobs_resources) click.clear() data = [['Job', 'Mem Usage/Limit', 'CPU%-CPUs', 'GPU Mem', 'GPU Usage']] for job_resources in jobs_resources: job_resources = ContainerResourcesConfig.from_dict(job_resources) line = [ job_resources.job_uuid.hex, '{} / {}'.format(job_resources.memory_used / (1024 ** 3), job_resources.memory_limit / (1024 ** 3)), '{} - {}'.format(job_resources.cpu_percentage, len(job_resources.percpu_percentage))] if job_resources.gpu_resources: pass data.append(line) click.echo(tabulate(data, headers="firstrow")) sys.stdout.flush()
def main(okta_profile, profile, verbose, force, awscli_args): """ Authenticate to awscli using Okta """ if not okta_profile: okta_profile = "default" aws_auth = AwsAuth(profile, verbose) if not aws_auth.check_sts_token(profile) or force: if verbose and force and profile: click.echo("Force option selected, getting new credentials anyway.") elif verbose and force: click.echo("Force option selected, but no profile provided. Option has no effect.") get_credentials(aws_auth, okta_profile, profile, verbose) if awscli_args: cmdline = ['aws', '--profile', profile] + list(awscli_args) if verbose: click.echo('Invoking: %s' % ' '.join(cmdline)) call(cmdline)
def get(ctx): """ Get key/values from an s3 json file. \b s3env prod get s3env staging get """ s3_key = get_key(ctx.obj["env"]) key_as_json = json.loads(s3_key.get()) if not key_as_json: click.echo("No key/values are currently set.") else: click.echo("Current key/values are...") for k, v in key_as_json.items(): click.echo("{}={}".format(k, v))
def set(ctx, key, value): """ Set a new key/value in an s3 json file. \b s3env prod set API_KEY "secret" s3env prod set DATABASE_URL sqlite3://mydatabase:password:user:9200 """ s3_key = get_key(ctx.obj["env"]) key_as_json = json.loads(s3_key.get()) key_as_json[key] = value s3_key.set(json.dumps(key_as_json, indent=4)) click.echo("Key successfully set.") click.echo("Current key/values are...") for k, v in key_as_json.items(): click.echo("{}={}".format(k, v))
def rm(ctx, key): """ Remove a key from an s3 json file. \b s3env prod rm API_KEY s3env staging rm DEBUG """ s3_key = get_key(ctx.obj["env"]) key_as_json = json.loads(s3_key.get()) try: del key_as_json[key] click.echo("Key removed.") except KeyError: raise click.ClickException("No key set for {}".format(key)) s3_key.set(json.dumps(key_as_json, indent=4)) if not key_as_json: click.echo("No key/values are currently set.") else: click.echo("Current key/values are...") for k, v in key_as_json.items(): click.echo("{}={}".format(k, v))
def webui(obj): '''List dashboard links for matching pods (if only one matched, URL is opened in browser).''' kubectl = obj.kubey.kubectl info = click.unstyle(kubectl.call_capture('cluster-info')) dash_endpoint = re.search(r'kubernetes-dashboard.*?(http\S+)', info).group(1) urls = [] for pod in obj.kubey.each_pod(obj.maximum): pod_path = '/#/pod/{0}/{1}?namespace={0}'.format(pod.namespace, pod.name) urls.append(dash_endpoint + pod_path) if len(urls) == 1: url = urls[0] click.echo(url) click.launch(url) else: for url in urls: click.echo(url)
def ctl_each(obj, command, arguments): '''Invoke any kubectl command directly for each pod matched and collate the output.''' width, height = click.get_terminal_size() kubectl = obj.kubey.kubectl collector = tabular.RowCollector() ns_pods = defaultdict(list) for pod in obj.kubey.each_pod(obj.maximum): ns_pods[pod.namespace].append(pod) for ns, pods in ns_pods.items(): args = ['-n', ns] + list(arguments) + [p.name for p in pods] kubectl.call_table_rows(collector.handler_for(ns), command, *args) kubectl.wait() if collector.rows: click.echo(tabular.tabulate(obj, sorted(collector.rows), collector.headers)) if kubectl.final_rc != 0: click.get_current_context().exit(kubectl.final_rc)
def createlog(name, filename): """ Create a log with the provided name and details. This method will use the JSON file first if both name and file are provided """ if filename is not None: with open(filename) as json_data: try: params = json.load(json_data) api.create_log(None, params) except ValueError as error: sys.stderr.write(error.message + '\n') sys.exit(1) elif name is not None: api.create_log(name, None) else: click.echo('Example usage: lecli create log -n new_log_name') click.echo('Example usage: lecli create log -f path_to_file.json')
def query(logkeys, favorites, logset, leql, timefrom, timeto, datefrom, dateto, relative_range, saved_query): """Query logs using LEQL""" success = api.query(log_keys=logkeys, query_string=leql, date_from=datefrom, date_to=dateto, time_from=timefrom, time_to=timeto, saved_query_id=saved_query, relative_time_range=relative_range, favorites=favorites, logset=logset) if not success: click.echo("Example usage: lecli query --logset mylogset --leql " "'where(method=GET) calculate(count)' " "--datefrom '2016-05-18 11:04:00' --dateto '2016-05-18 11:09:59' ") click.echo("Example usage: lecli query --favorites mylogalias --leql " "'where(method=GET) calculate(count)' " "--datefrom '2016-05-18 11:04:00' --dateto '2016-05-18 11:09:59' ") click.echo("Example usage: lecli query --favorites mylogalias --leql " "'where(method=GET) calculate(count)' " "-r 'last 3 days'")
def get_events(logkeys, favorites, logset, timefrom, timeto, datefrom, dateto, relative_range, saved_query): """Get log events""" success = api.query(log_keys=logkeys, time_from=timefrom, query_string=api.ALL_EVENTS_QUERY, time_to=timeto, date_from=datefrom, date_to=dateto, logset=logset, relative_time_range=relative_range, favorites=favorites, saved_query_id=saved_query) if not success: click.echo("Example usage: lecli get events 12345678-aaaa-bbbb-1234-1234cb123456 " "-f 1465370400 -t 1465370500") click.echo("Example usage: lecli get events 12345678-aaaa-bbbb-1234-1234cb123456 " "--datefrom '2016-05-18 11:04:00' --dateto '2016-05-18 11:09:59' ") click.echo("Example usage: lecli get events --logset mylogset " "--datefrom '2016-05-18 11:04:00' --dateto '2016-05-18 11:09:59' ") click.echo("Example usage: lecli get events --favorites mylogalias " "--datefrom '2016-05-18 11:04:00' --dateto '2016-05-18 11:09:59' ") click.echo("Example usage: lecli get events --favorites mylogalias " "-r 'last 3 hours'")
def get_recent_events(logkeys, favorites, logset, last, relative_range, saved_query): """Get recent log events""" start_time = now = None if not relative_range: now = time.time() start_time = now - last success = api.query(log_keys=logkeys, query_string=api.ALL_EVENTS_QUERY, time_from=start_time, time_to=now, relative_time_range=relative_range, favorites=favorites, logset=logset, saved_query_id=saved_query) if not success: click.echo( 'Example usage: lecli get recentevents 12345678-aaaa-bbbb-1234-1234cb123456 -l 200') click.echo('Example usage: lecli get recentevents -c mylogalias -l 200') click.echo('Example usage: lecli get recentevents -g mylogset -l 200') click.echo("Example usage: lecli get recentevents -g mylogset -r 'last 50 mins'")
def print_config_error_and_exit(section=None, config_key=None, value=None): """ Print appropriate apiutils error message and exit. """ if not section: click.echo("Error: Configuration file '%s' not found" % CONFIG_FILE_PATH, err=True) elif not config_key: click.echo("Error: Section '%s' was not found in configuration file(%s)" % (section, CONFIG_FILE_PATH), err=True) elif not value: click.echo("Error: Configuration key for %s was not found in configuration file(%s) in " "'%s' section" % (config_key, CONFIG_FILE_PATH, section), err=True) else: click.echo("Error: %s = '%s' is not in section: '%s' of your configuration file: '%s'" % (config_key, value, section, CONFIG_FILE_PATH), err=True) sys.exit(1)
def createlogset(name=None, filename=None): """ Create a logset with the provided name and details. This method will use the JSON file first if both name and file are provided """ if filename is not None: with open(filename) as json_data: try: params = json.load(json_data) api.create_logset(None, params) except ValueError as error: sys.stderr.write(error.message + '\n') sys.exit(1) elif name is not None: api.create_logset(name, None) else: click.echo('Example usage: lecli create logset -n new_log_name') click.echo('Example usage: lecli create logset -f path_to_file.json')
def delete_team(team_id): """ Delete a team with the provided team ID. """ headers = api_utils.generate_headers('rw') try: response = requests.delete(_url((team_id,))[1], headers=headers) if response_utils.response_error(response): # Check response has no errors click.echo('Delete team failed.', err=True) sys.exit(1) elif response.status_code == 204: click.echo('Deleted team with id: %s.' % team_id) except requests.exceptions.RequestException as error: click.echo(error, err=True) sys.exit(1)
def get_saved_query(query_id=None): """ If query id is provided, get this specific saved query or get them all :param query_id: uuid of saved query to be retrieved(optional) """ endpoint_url = _url()[1] if query_id: endpoint_url = _url((query_id,))[1] headers = api_utils.generate_headers('rw') try: response = requests.get(endpoint_url, headers=headers) if response_utils.response_error(response): if query_id: sys.stderr.write("Unable to retrieve saved query with id %s" % query_id) else: sys.stderr.write("Unable to retrieve saved queries.") elif response.status_code == 200: _handle_saved_query_response(response) except requests.exceptions.RequestException as error: click.echo(error) sys.exit(1)
def create(ctx, maintype, subtype, app_name, factory, args): args = args or [] maintype = maintype or ctx.obj['SETTINGS'].get( 'default_maintype', 'python') subtype = subtype or ctx.obj['SETTINGS'].get( 'default_subtype', 'app') click.echo('Type: {};\t Subtype: {};\t App name: {};'.format( maintype, subtype, app_name)) current_dir = os.getcwd() additional_dirs = ctx.obj['SETTINGS'].get('templates', []) factory_module, path = get_factory(maintype, factory, additional_dirs) if not factory_module: click.echo('ERROR: factory not found:{}'.format(maintype), err=True) exit(1) app_factory = factory_module.AppFactory(path, args) app_factory.setup(subtype, app_name, current_dir) app_factory.set_context(ctx.obj['SETTINGS'].get('context', {})) app_factory.run() click.echo('Done!')
def delete(ctx, service_name, dry_run): """ Delete the service SERVICE_NAME from AWS. """ service = Service(yml=Config(filename=ctx.obj['CONFIG_FILE'], env_file=ctx.obj['ENV_FILE']).get_service(service_name)) print() click.secho('Deleting service "{}":'.format(service.serviceName), fg="white") click.secho(' Service info:', fg="green") print_service_info(service) click.secho(' Task Definition info:', fg="green") print_task_definition(service.active_task_definition) print() if not dry_run: click.echo("If you really want to do this, answer \"{}\" to the question below.\n".format(service.serviceName)) value = click.prompt("What service do you want to delete? ") if value == service.serviceName: service.scale(0) print(" Waiting for our existing containers to die ...") service.wait_until_stable() print(" All containers dead.") service.delete() print(" Deleted service {} from cluster {}.".format(service.serviceName, service.clusterName)) else: click.echo("\nNot deleting service \"{}\"".format(service.serviceName))
def cluster_ssh(ctx, service_name): """ SSH to the specified EC2 system in the ECS cluster running SERVICE_NAME. """ service = Service( yml=Config(filename=ctx.obj['CONFIG_FILE'], env_file=ctx.obj['ENV_FILE']).get_service(service_name)) ips = service.get_host_ips() for index, ip in enumerate(ips): click.echo("Instance {}: {}".format(index+1, ip)) instance = click.prompt("Which instance to ssh to?", type=int) if instance > len(ips): click.echo("That is not a valid instance.") return instance_ip = ips[instance-1] service.cluster_ssh(instance_ip)
def _format_requirements(project_dir, requirements): """Prepare cmds for project requirements""" rel_reqs_path = os.path.relpath( os.path.join(project_dir, requirements), project_dir) if os.path.isfile(rel_reqs_path): if rel_reqs_path.startswith('../'): raise shub_exceptions.BadParameterException( "requirements file must be inside your project directory" "(it's a demand of docker itself)") else: # let's create requirements.txt with base dependencies with open(rel_reqs_path, 'w') as reqs_file: reqs_file.writelines("%s\n" % l for l in BASE_PYTHON_DEPS) click.echo('Created base requirements.txt in project dir.') rows = [ 'COPY ./{} {}/requirements.txt'.format(rel_reqs_path, DOCKER_APP_DIR), 'RUN pip install --no-cache-dir -r requirements.txt', ] return '\n'.join(rows)
def push_cmd(target, version, username, password, email, apikey, insecure): client = utils.get_docker_client() config = utils.load_release_config() image = config.get_image(target) username, password = utils.get_credentials( username=username, password=password, insecure=insecure, apikey=apikey, target_apikey=config.get_apikey(target)) if username: _execute_push_login(client, image, username, password, email) image_name = utils.format_image_name(image, version) click.echo("Pushing {} to the registry.".format(image_name)) for data in client.push(image_name, stream=True, decode=True, insecure_registry=not bool(username)): if 'status' in data: utils.debug_log("Logs:{} {}".format(data['status'], data.get('progress'))) if 'error' in data: click.echo("Error {}: {}".format(data['error'], data['errorDetail'])) raise shub_exceptions.RemoteErrorException( "Docker push operation failed") click.echo("The image {} pushed successfully.".format(image_name))
def list_cmd_full(target, silent, version): config = utils.load_release_config() image = config.get_image(target) version = version or config.get_version() image_name = utils.format_image_name(image, version) project, endpoint, apikey = None, None, None try: project, endpoint, apikey = config.get_target(target) except shub_exceptions.BadParameterException as exc: if 'Could not find target' not in exc.message: raise if not silent: click.echo( "Not found project for target {}, " "not getting project settings from Dash.".format(target)) spiders = list_cmd(image_name, project, endpoint, apikey) for spider in spiders: click.echo(spider)
def list_cmd(image_name, project, endpoint, apikey): """Short version of list cmd to use with deploy cmd.""" settings = {} if project: settings = _get_project_settings(project, endpoint, apikey) # Run a local docker container to run list-spiders cmd status_code, logs = _run_list_cmd(project, image_name, settings) if status_code != 0: click.echo(logs) raise shub_exceptions.ShubException( 'Container with list cmd exited with code %s' % status_code) spiders = utils.valid_spiders( logs.decode('utf-8') if isinstance(logs, binary_type) else logs) return spiders
def store_status_url(status_url, limit): """Load status file and update it with a url""" data = _load_status_file(STATUS_FILE_LOCATION) if not data: data[0] = status_url _update_status_file(data, STATUS_FILE_LOCATION) return 0 for stored_id, stored_url in data.items(): if stored_url == status_url: click.echo("Found same status_url: {}".format(stored_id)) return stored_id status_id = max(data.keys()) + 1 data[status_id] = status_url if len(data) > limit: data.popitem() _update_status_file(data, STATUS_FILE_LOCATION) return status_id
def load_status_url(status_id): """ Load status url from file by status_id""" if not os.path.isfile(STATUS_FILE_LOCATION): raise shub_exceptions.NotFoundException( 'Status file is not found at {}'.format(STATUS_FILE_LOCATION)) data = _load_status_file(STATUS_FILE_LOCATION) # return latest status url if status id is not provided if not isinstance(status_id, int) and data: max_status_id = max(data.keys()) click.echo('Getting results for latest status id {}.' .format(max_status_id)) return data[max_status_id] if status_id not in data: raise shub_exceptions.NotFoundException( "Status url with id {} is not found".format(status_id)) return data[status_id]
def print_project_status(ctx): config = ctx.obj.config solution_num = ctx.obj.solution_num project_status = gather_project_status(ctx) # Print out a 'pretty' message showing project status, first up some project details click.secho("Project Details", bold=True) click.echo(" Project Name: " + config["project_name"]) click.echo(" Number of solutions generated: " + str(solution_num)) click.echo(" Latest Solution Folder: '" + config["project_name"] + "/solution" + str(solution_num) + "'") click.echo(" Language Choice: " + config["language"]) # And now details about what builds have been run/are passing. # This section uses lots (too many!) 'conditional expressions' to embed formatting into the output. click.secho("Build Status", bold=True) click.echo(" C Simulation: " + (click.style("Pass", fg='green') if "csim_pass" in project_status else (click.style("Fail", fg='red') if "csim_fail" in project_status else (click.style("Run (Can't get status)", fg='yellow') if "csim_done" in project_status else click.style("Not Run", fg='yellow'))))) click.echo(" C Synthesis: " + (click.style("Run", fg='green') if "syn_done" in project_status else click.style("Not Run", fg='yellow'))) click.echo(" Cosimulation: " + (click.style("Pass", fg='green') if "cosim_pass" in project_status else (click.style("Fail", fg='red') if "cosim_fail" in project_status else (click.style("Run (Can't get status)", fg='yellow') if "cosim_done" in project_status else click.style("Not Run", fg='yellow'))))) click.echo(" Export:" ) click.echo(" IP Catalog: " + (click.style("Run", fg='green') if "export_ip_done" in project_status else click.style("Not Run", fg='yellow'))) click.echo(" System Generator: " + (click.style("Run", fg='green') if "export_sysgen_done" in project_status else click.style("Not Run", fg='yellow'))) click.echo(" Export Evaluation: " + (click.style("Run", fg='green') if "evaluate_done" in project_status else click.style("Not Run", fg='yellow'))) ### Click Command Definitions ### # Report Command
def do_start_build_stuff(ctx): config = ctx.obj.config solution_num = ctx.obj.solution_num try: file = click.open_file("run_hls.tcl","w") file.write("open_project " + config["project_name"] + "\n") file.write("set_top " + config["top_level_function_name"] + "\n") for src_file in config["src_files"]: file.write("add_files " + config["src_dir_name"] + "/" + src_file + "\n") for tb_file in config["tb_files"]: file.write("add_files -tb " + config["tb_dir_name"] + "/" + tb_file + "\n") if ctx.params['keep']: file.write("open_solution -reset \"solution" + str(solution_num) + "\"" + "\n") else: file.write("open_solution \"solution" + str(solution_num) + "\"" + "\n") file.write("set_part \{" + config["part_name"] + "\}" + "\n") file.write("create_clock -period " + config["clock_period"] + " -name default" + "\n") return file except OSError: click.echo("Woah! Couldn't create a Tcl run file in the current folder!") raise click.Abort() # Function to write a default build into the HLS Tcl build script.
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 hls_processs = subprocess.run(["vivado_hls", "-f", "run_hls.tcl"]) # Check return status of the HLS process. if hls_processs.returncode < 0: raise click.Abort() elif hls_processs.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
def get_dependencies(ctx, archive_name, version): ''' List the dependencies of an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) deps = [] dependencies = var.get_dependencies(version=version) for arch, dep in dependencies.items(): if dep is None: deps.append(arch) else: deps.append('{}=={}'.format(arch, dep)) click.echo('\n'.join(deps))
def download(ctx, archive_name, filepath, version): ''' Download an archive ''' _generate_api(ctx) var = ctx.obj.api.get_archive(archive_name) if version is None: version = var.get_default_version() var.download(filepath, version=version) archstr = var.archive_name +\ '' if (not var.versioned) else ' v{}'.format(version) click.echo('downloaded{} to {}'.format(archstr, filepath))
def show(self): env_info = super(CliEnv, self).show() msg = prettytable.PrettyTable( header_style='upper', padding_width=5, field_names=['Functest Environment', 'value']) for key, value in six.iteritems(env_info): if key is not None: msg.add_row([key, value]) click.echo(msg.get_string())
def call(self, args, devnull=False): """Call other processes. args - list of command args devnull - whether to pipe stdout to /dev/null (or equivalent) """ if self.debug: click.echo(subprocess.list2cmdline(args)) click.confirm('Continue?', default=True, abort=True) try: kwargs = {} if devnull: # Pipe to /dev/null (or equivalent). kwargs['stderr'] = subprocess.STDOUT kwargs['stdout'] = self.FNULL ret_code = subprocess.call(args, **kwargs) except subprocess.CalledProcessError: return False return ret_code
def export(mark, file, fenv): """ Export U-Boot environment variables """ try: envimg = uboot.EnvImgOld(start_string=mark) envimg.open_img(file) with open(fenv, 'w') as f: f.write(envimg.store()) except Exception as e: click.echo(str(e) if str(e) else "Unknown Error !") sys.exit(ERROR_CODE) click.secho("Environment variables saved into: %s" % fenv) # U-Boot envimg: Update U-Boot environment variables
def replace(mark, file, fenv): """ Replace U-Boot environment variables """ try: envimg = uboot.EnvImgOld(start_string=mark) envimg.open_img(file) envimg.clear() with open(fenv, 'r') as f: envimg.load(f.read()) envimg.save_img(file) except Exception as e: click.echo(str(e) if str(e) else "Unknown Error !") sys.exit(ERROR_CODE) click.echo(str(envimg))
def info(offset, size, file): """ List image content """ try: env = uboot.EnvBlob() with open(file, "rb") as f: f.seek(offset) data = f.read(size) env.parse(data) env.size = len(data) except Exception as e: click.echo(str(e) if str(e) else "Unknown Error !") sys.exit(ERROR_CODE) click.echo(str(env)) # U-Boot mkenv: Create new image from attached file
def extract(offset, size, file): """ Extract image content """ try: fileName, _ = os.path.splitext(file) env = uboot.EnvBlob(size=size) with open(file, "rb") as f: f.seek(offset) env.parse(f.read()) with open(fileName + '.txt', 'w') as f: f.write(env.store()) except Exception as e: click.echo(str(e) if str(e) else "Unknown Error !") sys.exit(ERROR_CODE) click.secho(" Successfully extracted: %s.txt" % fileName)
def get(ctx, keyword): """ Print a configuration setting. \b Example: farmer config get api_url """ config = ctx.obj['config'] try: value = operator.attrgetter(keyword)(config) except AttributeError as exc: raise click.ClickException(exc.message) if isinstance(value, SCALARS): click.echo(value) else: # Resolve top-most LayeredConfig config and dump it as YAML. click.echo(dump_yaml(value))
def list_apps(ctx): environment = ctx.parent.params['environment'] config_parser = configparser.ConfigParser() config_parser.read(CONFIG_PATH) if sys.version_info[0] < 3 and environment.lower() == 'default': environment = configparser.DEFAULTSECT client_id = config_parser.get(environment, 'client_id') client_secret = config_parser.get(environment, 'client_secret') response = management_utils.list_apps((client_id, client_secret)) if response.ok: app_data = response.json() else: click.echo(response.text) printer = pprint.PrettyPrinter(indent=4) printer.pprint(app_data)
def readFasta(fastaFile): """ Reads a FASTA file and parses contigs for GC content. Args: fastaFile: The path to the FASTA file. Returns: contigs A dictionary mapping contigIDs to sidr.common.Contig objects with GC content as a variable. """ contigs = [] if ".gz" in fastaFile: # should support .fa.gz files in a seamless (if slow) way openFunc = gzip.open else: openFunc = open with openFunc(fastaFile) as data: click.echo("Reading %s" % fastaFile) with click.progressbar(FastaIterator(data)) as fi: for record in fi: # TODO: conditional formatting contigs.append(common.Contig(record.id.split(' ')[0], variables={"GC": GC(record.seq)})) if len(contigs) != len(set([x.contigid for x in contigs])): # exit if duplicate contigs, https://stackoverflow.com/questions/5278122/checking-if-all-elements-in-a-list-are-unique raise ValueError("Input FASTA contains duplicate contigIDs, exiting") return dict((x.contigid, x) for x in contigs) # https://stackoverflow.com/questions/3070242/reduce-python-list-of-objects-to-dict-object-id-object
def runAnalysis(bam, fasta, blastresults, taxdump, modelOutput, output, tokeep, toremove, binary, target, level): taxdump, taxidDict = common.parseTaxdump(taxdump, False) gc.collect() click.echo("Taxdump parsed, %d taxIDs loaded" % len(taxdump)) contigs = readFasta(fasta) gc.collect() click.echo("FASTA loaded, %d contigs returned" % len(contigs)) contigs = readBAM(bam, contigs) gc.collect() click.echo("BAM loaded") contigs, classMap, classList = readBLAST(blastresults, taxdump, level.lower(), contigs) gc.collect() click.echo("BLAST results loaded") corpus, testdata, features = common.constructCorpus(list(contigs.values()), classMap, binary, target) gc.collect() click.echo("Corpus constucted, %d contigs in corpus and %d contigs in test data" % (len(corpus), len(testdata))) classifier = common.constructModel(corpus, classList, features, modelOutput) result = common.classifyData(classifier, testdata, classMap) common.generateOutput(tokeep, toremove, result, contigs.values(), target, output)
def update_release(channel): """ Update release manifests. """ if not os.path.exists("cluster.yml"): error("no cluster.yml found. Did you configure?") with open("cluster.yml") as fp: config = yaml.load(fp.read()) if channel is None: channel = config["release"]["channel"] current_version = config["release"]["version"] configure.release(config, channel) if current_version == config["release"]["version"]: click.echo("No updates available for {} channel".format(channel)) sys.exit(0) with open("cluster.yml", "w") as fp: fp.write(yaml.safe_dump(config, default_flow_style=False)) click.echo("Updated config to {} in {} channel".format(config["release"]["version"], config["release"]["channel"]))
def up(component): """ Bring Layer 1 online. """ if not os.path.exists("cluster.yml"): error("cluster.yml does not exist. Did you configure?") with open("cluster.yml") as fp: config = yaml.load(fp.read()) cluster = Cluster(config) cluster.key_keeper = KeyKeeper("./keys") if not component: components = COMPONENTS.values() else: components = [] for c in component: try: components.append(COMPONENTS[c]) except KeyError: error("\"{}\" is not an available component.".format(c)) for Component in components: Component(cluster).create() click.echo("Done.")
def get_str_content(str_value): """ Returns the string content of a passed yaml content value (for an insert/replace yamlpal operation). If the passed str_value starts with an '@' then we attempt to treat the passed string as a filename and read the contents of the file.""" if str_value.startswith("@"): file_path = str_value[1:] if not os.path.isfile(file_path): click.echo("ERROR: Invalid file content path '%s'." % file_path, err=True) exit(1) with open(file_path, 'r') as f: content = f.read() # strip off newline at the end if it's there: insert/replace takes care of this if content.endswith("\n"): content = content[0:-1] else: # If we directly pass the string, strip whitespace and allow newline and tab chars content = str_value.strip().replace("\\n", "\n").replace("\\t", "\t") return content
def main(number=None): """Console script for rust_pypi_example The console script takes a singe argument, "NUMBER", which must be an integer greater than 2. The script calls out to a library written in Rust to compute whether the intger is a prime number. Example: rust_pypi_example 13 """ if number and number > 2: click.echo(True if rust_lib.is_prime(number) else False) else: click.echo("Please supply an integer argument greater than 2. The " "console script will tell you if it is a prime number")
def main(names): click.echo(repr(names))
def check_cli_version(): """Check if the current cli version satisfies the server requirements""" try: server_version = PolyaxonClients().version.get_cli_version() except (PolyaxonHTTPError, PolyaxonShouldExitError) as e: Printer.print_error('Could not get cli version.') Printer.print_error('Error message `{}`.'.format(e)) sys.exit(1) current_version = pkg_resources.get_distribution(PROJECT_CLI_NAME).version if LooseVersion(current_version) < LooseVersion(server_version.min_version): click.echo("""Your version of CLI ({}) is no longer compatible with server.""".format( current_version)) if click.confirm("Do you want to upgrade to " "version {} now?".format(server_version.latest_version)): pip_upgrade() sys.exit(0) else: clint.textui.puts("Your can manually run:") with clint.textui.indent(4): clint.textui.puts("pip install -U polyaxon-cli") clint.textui.puts( "to upgrade to the latest version `{}`".format(server_version.latest_version)) sys.exit(0) elif LooseVersion(current_version) < LooseVersion(server_version.latest_version): clint.textui.puts("New version of CLI ({}) is now available. To upgrade run:".format( server_version.latest_version )) with clint.textui.indent(4): clint.textui.puts("pip install -U polyaxon-cli")