Python click.clear() Examples
The following are 30
code examples of click.clear().
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: formatting.py From polyaxon with Apache License 2.0 | 6 votes |
def resources(cls, jobs_resources): jobs_resources = to_list(jobs_resources) click.clear() data = [["Job", "Mem Usage / Total", "CPU% - CPUs"]] for job_resources in jobs_resources: job_resources = ContainerResourcesConfig.from_dict(job_resources) line = [ job_resources.job_name, "{} / {}".format( to_unit_memory(job_resources.memory_used), to_unit_memory(job_resources.memory_limit), ), "{} - {}".format( to_percentage(job_resources.cpu_percentage / 100), job_resources.n_cpus, ), ] data.append(line) click.echo(tabulate(data, headers="firstrow")) sys.stdout.flush()
Example #2
Source File: formatting.py From polyaxon-cli with MIT License | 5 votes |
def resources(cls, jobs_resources): jobs_resources = to_list(jobs_resources) click.clear() data = [['Job', 'Mem Usage / Total', 'CPU% - CPUs']] for job_resources in jobs_resources: job_resources = ContainerResourcesConfig.from_dict(job_resources) line = [ job_resources.job_name, '{} / {}'.format(to_unit_memory(job_resources.memory_used), to_unit_memory(job_resources.memory_limit)), '{} - {}'.format(to_percentage(job_resources.cpu_percentage / 100), job_resources.n_cpus)] data.append(line) click.echo(tabulate(data, headers="firstrow")) sys.stdout.flush()
Example #3
Source File: main.py From wharfee with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clear(self): """ Clear the screen. """ click.clear()
Example #4
Source File: main.py From wharfee with BSD 3-Clause "New" or "Revised" License | 5 votes |
def __init__(self, no_completion=False): """ Initialize class members. Should read the config here at some point. """ self.config = self.read_configuration() self.theme = self.config['main']['theme'] log_file = self.config['main']['log_file'] log_level = self.config['main']['log_level'] self.logger = create_logger(__name__, log_file, log_level) # set_completer_options refreshes all by default self.handler = DockerClient( self.config['main'].as_int('client_timeout'), self.clear, self.refresh_completions_force, self.logger) self.completer = DockerCompleter( long_option_names=self.get_long_options(), fuzzy=self.get_fuzzy_match()) self.set_completer_options() self.completer.set_enabled(not no_completion) self.saved_less_opts = self.set_less_opts()
Example #5
Source File: util.py From planet-client-python with Apache License 2.0 | 5 votes |
def _do_output(self): # renders a terminal like: # highlighted status rows # .... # # scrolling log output # ... width, height = click.termui.get_terminal_size() wrapper = textwrap.TextWrapper(width=width) self._stats['elapsed'] = '%d' % (time.time() - self._start) stats = ['%s: %s' % (k, v) for k, v in sorted(self._stats.items())] stats = wrapper.wrap(''.join([s.ljust(25) for s in stats])) remaining = height - len(stats) - 2 stats = [s.ljust(width) for s in stats] lidx = max(0, len(self._records) - remaining) loglines = [] while remaining > 0 and lidx < len(self._records): wrapped = wrapper.wrap(self._records[lidx]) while remaining and wrapped: loglines.append(wrapped.pop(0)) remaining -= 1 lidx += 1 # clear/cursor-to-1,1/hightlight click.echo(u'\u001b[2J\u001b[1;1H\u001b[30;47m' + '\n'.join(stats) # unhighlight + u'\u001b[39;49m\n' + '\n'.join(loglines))
Example #6
Source File: util.py From planet-client-python with Apache License 2.0 | 5 votes |
def start(self): click.clear() _BaseOutput.start(self)
Example #7
Source File: cmd_arp_sniff.py From habu with BSD 3-Clause "New" or "Revised" License | 5 votes |
def procpkt(pkt): now = time() output = '{seconds}\t{ip}\t{hwaddr}\t{vendor}' if conf.manufdb: manufdb_available = True else: manufdb_available = False if 'ARP' in pkt: hosts[pkt[ARP].psrc] = {} hosts[pkt[ARP].psrc]['hwaddr'] = pkt[ARP].hwsrc hosts[pkt[ARP].psrc]['time'] = time() if manufdb_available: hosts[pkt[ARP].psrc]['vendor'] = conf.manufdb._get_manuf(pkt[ARP].hwsrc) else: hosts[pkt[ARP].psrc]['vendor'] = 'unknown' click.clear() if not manufdb_available: click.echo('WARNING: manufdb is not available. Can\'t get vendor.') for ip in sorted(hosts): print(output.format( seconds = int(now - hosts[ip]['time']), ip = ip, hwaddr = hosts[ip]['hwaddr'], vendor = hosts[ip]['vendor'] ))
Example #8
Source File: manage.py From beijing_bus with MIT License | 5 votes |
def cli(): q = click.prompt('请输入线路名', value_proc=str) lines = BeijingBus.search_lines(q) for index, line in enumerate(lines): click.echo() click.secho('[%s] %s' % (index+1, line.name), bold=True, underline=True) station_names = [s.name for s in line.stations] click.echo() click.echo('站点列表:%s' % ','.join(station_names)) click.echo() q = click.prompt('请从结果中选择线路编号', type=int) line = lines[q-1] click.clear() click.echo('你选择了 %s,下面请选择站点' % line.name) click.echo() for index, station in enumerate(line.stations): click.echo('[%s] %s' % (index+1, station.name)) click.echo() q = click.prompt('请从结果中选择线路编号', type=int) while True: echo_realtime_data(line, q) time.sleep(5)
Example #9
Source File: manage.py From beijing_bus with MIT License | 5 votes |
def echo_realtime_data(line, station_num): station = line.stations[station_num-1] realtime_data = line.get_realtime_data(station_num) click.clear() now = datetime.now().strftime('%H:%M:%S') title = '实时数据 [%s] 线路:%s (每5秒自动刷新,更新于%s)' % (station.name, line.name, now) click.secho(title, fg='green', bold=True) click.echo() realtime_data = filter(lambda d: d['station_arriving_time'], realtime_data) realtime_data.sort(key=lambda d: d['station_arriving_time']) for i, data in enumerate(realtime_data): click.secho('公交%s:' % (i+1), bold=True, underline=True) click.echo('距离 %s 还有%s米' % (station.name, data['station_distance'])) click.echo('预计 %s 到达' % data['station_arriving_time'].strftime('%H:%M')) click.echo()
Example #10
Source File: ctl.py From patroni with MIT License | 5 votes |
def watching(w, watch, max_count=None, clear=True): """ >>> len(list(watching(True, 1, 0))) 1 >>> len(list(watching(True, 1, 1))) 2 >>> len(list(watching(True, None, 0))) 1 """ if w and not watch: watch = 2 if watch and clear: click.clear() yield 0 if max_count is not None and max_count < 1: return counter = 1 while watch and counter <= (max_count or counter): time.sleep(watch) counter += 1 if clear: click.clear() yield 0
Example #11
Source File: output.py From http-prompt with MIT License | 5 votes |
def clear(self): click.clear()
Example #12
Source File: __init__.py From jesse with MIT License | 5 votes |
def optimize_mode(start_date: str, finish_date: str): # clear the screen click.clear() print('loading candles...') click.clear() # load historical candles and divide them into training # and testing candles (15% for test, 85% for training) training_candles, testing_candles = get_training_and_testing_candles(start_date, finish_date) optimizer = Optimizer(training_candles, testing_candles) optimizer.run() # TODO: store hyper parameters into each strategies folder per each Exchange-symbol-timeframe
Example #13
Source File: formatting.py From polyaxon-cli with MIT License | 5 votes |
def gpu_resources(cls, jobs_resources): jobs_resources = to_list(jobs_resources) click.clear() data = [ ['job_name', 'name', 'GPU Usage', 'GPU Mem Usage / Total', 'GPU Temperature', 'Power Draw / Limit'] ] non_gpu_jobs = 0 for job_resources in jobs_resources: job_resources = ContainerResourcesConfig.from_dict(job_resources) line = [] if not job_resources.gpu_resources: non_gpu_jobs += 1 continue for gpu_resources in job_resources.gpu_resources: line += [ job_resources.job_name, gpu_resources.name, to_percentage(gpu_resources.utilization_gpu / 100), '{} / {}'.format( to_unit_memory(gpu_resources.memory_used), to_unit_memory(gpu_resources.memory_total)), gpu_resources.temperature_gpu, '{} / {}'.format(gpu_resources.power_draw, gpu_resources.power_limit), ] data.append(line) if non_gpu_jobs == len(jobs_resources): Printer.print_error( 'No GPU job was found, please run `resources` command without `-g | --gpu` option.') exit(1) click.echo(tabulate(data, headers="firstrow")) sys.stdout.flush()
Example #14
Source File: cli.py From Google-Images-Search with MIT License | 5 votes |
def search(ctx, query, num, safe, filetype, imagetype, imagesize, dominantcolor, download_path, width, height): search_params = { 'q': query, 'num': num, 'safe': safe, 'fileType': filetype, 'imgType': imagetype, 'imgSize': imagesize, 'imgDominantColor': dominantcolor } click.clear() try: ctx.obj['object'].search(search_params, download_path, width, height) for image in ctx.obj['object'].results(): click.echo(image.url) if image.path: click.secho(image.path, fg='blue') if not image.resized: click.secho('[image is not resized]', fg='red') else: click.secho('[image is not download]', fg='red') click.echo() except GoogleBackendException: click.secho('Error occurred trying to fetch ' 'images from Google. Please try again.', fg='red') return
Example #15
Source File: domain_commands.py From fandogh-cli with MIT License | 5 votes |
def _display_domain_details(domain_details, clear=True): if clear: click.clear() click.echo('Domain: {}'.format(format_text(domain_details['name'], TextStyle.HEADER))) if domain_details['verified'] is True: click.echo('\tVerified: {}'.format(format_text("Yes", TextStyle.OKGREEN))) else: click.echo('\tVerified: {}'.format(format_text("Yes", TextStyle.FAIL))) if domain_details.get('certificate', None) is None: click.echo("\tCertificate: {}".format(format_text("Not requested", TextStyle.OKBLUE))) else: certificate_details = domain_details['certificate'].get('details') status = certificate_details['status'] if status == 'PENDING': click.echo("\tCertificate: {}".format(format_text('Trying to get a certificate', TextStyle.OKBLUE))) elif status == 'ERROR': click.echo("\tCertificate: {}".format(format_text('Getting certificate failed', TextStyle.FAIL))) elif status == 'READY': click.echo("\tCertificate: {}".format(format_text('Certificate is ready to use', TextStyle.OKGREEN))) else: click.echo('\tCertificate: {}'.format(format_text('Certificate status is unknown', TextStyle.WARNING))) info = certificate_details.get("info", False) if info: click.echo('\tInfo: {}'.format(format_text(info, TextStyle.WARNING))) if len(certificate_details.get('events', [])) > 0: click.echo("\tEvents:") for condition in certificate_details.get("events", []): click.echo("\t + {}".format(condition))
Example #16
Source File: config.py From anime-downloader with The Unlicense | 5 votes |
def traverse_json(data, previous=''): click.clear() keys = list(data.keys()) click.echo(create_table(keys, previous)) val = click.prompt("Select Option", type = int, default = 1) - 1 if type(data[keys[val]]) == dict: traverse_json(data[keys[val]], keys[val]) else: click.echo(f"Current value: {data[keys[val]]}") newVal = click.prompt(f"Input new value for {keys[val]}", type = str) #Normal strings cause an error try: newVal = eval(newVal) except (SyntaxError, NameError) as e: pass if type(newVal) != type(data[keys[val]]): choice = click.confirm(f"{newVal} appears to be of an incorrect type. Continue") if not choice: exit() elif data[keys[val]] is not None: try: newVal = type(data[keys[val]])(newVal) except TypeError: click.echo(f"'{newVal}' could not be converted to the correct type") exit() data[keys[val]] = newVal
Example #17
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def get_ansible_ssh_user(): click.clear() message = """ This installation process involves connecting to remote hosts via ssh. Any account may be used. However, if a non-root account is used, then it must have passwordless sudo access. """ click.echo(message) return click.prompt('User for ssh access', default='root')
Example #18
Source File: grpc_shell.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clear(): click.clear()
Example #19
Source File: grpc_shell.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clear(ctx): ''' Clears request, response and error fields. ''' ctx.obj['manager'].rpcs[ctx.obj['RPC_TYPE']][ctx.obj['RPC_NAME']].clear()
Example #20
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def get_routingconfig_subdomain(): click.clear() message = """ You might want to override the default subdomain used for exposed routes. If you don't know what this is, use the default value. """ click.echo(message) return click.prompt('New default subdomain (ENTER for none)', default='')
Example #21
Source File: grpc_shell.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clear(ctx): ''' Removes subscriptions from this rpc. ''' try: ctx.obj['manager'].rpcs[ctx.obj['RPC_TYPE']][ctx.obj['RPC_NAME']].clear() except Exception as e: click.secho('\n{0}\n'.format(e), fg='red')
Example #22
Source File: grpc_shell.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clear(ctx): ''' Clears request, response and error fields. ''' ctx.obj['manager'].rpcs[ctx.obj['RPC_TYPE']][ctx.obj['RPC_NAME']].clear()
Example #23
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 5 votes |
def collect_new_nodes(oo_cfg): click.clear() click.echo('*** New Node Configuration ***') message = """ Add new nodes here """ click.echo(message) new_nodes, _ = collect_hosts(oo_cfg, existing_env=True, masters_set=True, print_summary=False) return new_nodes
Example #24
Source File: domain_commands.py From fandogh-cli with MIT License | 5 votes |
def details(name): """ Get details of a domain """ _display_domain_details(details_domain(name), clear=False)
Example #25
Source File: grpc_shell.py From SROS-grpc-services with BSD 3-Clause "New" or "Revised" License | 5 votes |
def clear(ctx): ''' Clears request, response and error fields. ''' ctx.obj['manager'].rpcs[ctx.obj['RPC_TYPE']][ctx.obj['RPC_NAME']].clear()
Example #26
Source File: command_line.py From Dallinger with MIT License | 5 votes |
def monitor(app): """Set up application monitoring.""" heroku_app = HerokuApp(dallinger_uid=app) webbrowser.open(heroku_app.dashboard_url) webbrowser.open("https://requester.mturk.com/mturk/manageHITs") heroku_app.open_logs() check_call(["open", heroku_app.db_uri]) while _keep_running(): summary = get_summary(app) click.clear() click.echo(header) click.echo("\nExperiment {}\n".format(app)) click.echo(summary) time.sleep(10)
Example #27
Source File: graph.py From FB-Spider with MIT License | 5 votes |
def initialise(): click.clear() click.secho("Enter the User access token", fg="green", bold=True) token = input() click.secho( "Enter the no of result pages for your input.\nBy default it is set to 5.", fg="green", bold=True) try: val = int(input()) npa = val except ValueError: npa = 5 click.secho( "Enter the no of posts in the output page.\nBy default it is set to 5.", fg="green", bold=True) try: val = int(input()) npo = val except ValueError: npo = 5 click.clear() click.secho("Data initialised succesfully", fg="green", bold=True) with open("userdata.json", "w") as outfile: data = {'token': token, 'npa': npa, 'npo': npo} json.dump(data, outfile) # shows the data stored in userdata.json file
Example #28
Source File: actions.py From drive-cli with MIT License | 4 votes |
def history(date, clear): if clear: click.confirm('Do you want to continue?', abort=True) click.secho("deleting.....", fg='magenta') utils.clear_history() click.secho("successfully deleted", fg='green') cwd = os.getcwd() utils.save_history([{"--date": [date], "--clear":["True"]}, "", cwd]) else: cwd = os.getcwd() utils.save_history([{"--date": [date], "--clear":[None]}, "", cwd]) History = utils.get_history() if date != None: if date in History: history = History[date] for i in history: click.secho(date + " " + i, fg='yellow', bold=True) click.secho("working directory : " + history[i]["cwd"], bold=True) click.secho("command : " + history[i]["command"]) if(history[i]["arg"] != ""): click.secho("argument : " + history[i]["arg"]) if(len(history[i]["flags"]) != 0): flag_val = "" for j in history[i]["flags"]: if(history[i]["flags"][j][0] != None): val = ", ".join(history[i]["flags"][j]) flag_val = flag_val + "\t" + j + " : " + val + "\n" if(flag_val != ""): click.secho("flags : ", bold=True) click.secho(flag_val) click.secho("\n") else: click.secho("No histrory found!!!", fg='red') else: if len(History) == 0: click.secho("No histrory found!!!", fg='red') else: for date in History: history = History[date] for i in history: click.secho(date + " " + i, fg='yellow', bold=True) click.secho("working directory : " + history[i]["cwd"], bold=True) click.secho("command : " + history[i]["command"]) if(history[i]["arg"] != ""): click.secho("argument : " + history[i]["arg"]) if(len(history[i]["flags"]) != 0): flag_val = "" for j in history[i]["flags"]: if(history[i]["flags"][j][0] != None): val = ", ".join(history[i]["flags"][j]) flag_val = flag_val + "\t" + j + " : " + val + "\n" if(flag_val != ""): click.secho("flags : ", bold=True) click.secho(flag_val) click.secho("\n")
Example #29
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 4 votes |
def print_installation_summary(hosts, version=None, verbose=True): """ Displays a summary of all hosts configured thus far, and what role each will play. Shows total nodes/masters, hints for performing/modifying the deployment with additional setup, warnings for invalid or sub-optimal configurations. """ click.clear() click.echo('*** Installation Summary ***\n') click.echo('Hosts:') for host in hosts: print_host_summary(hosts, host) masters = [host for host in hosts if host.is_master()] nodes = [host for host in hosts if host.is_node()] dedicated_nodes = [host for host in hosts if host.is_node() and not host.is_master()] click.echo('') click.echo('Total OpenShift masters: %s' % len(masters)) click.echo('Total OpenShift nodes: %s' % len(nodes)) if verbose: if len(masters) == 1 and version != '3.0': ha_hint_message = """ NOTE: Add a total of 3 or more masters to perform an HA installation.""" click.echo(ha_hint_message) elif len(masters) == 2: min_masters_message = """ WARNING: A minimum of 3 masters are required to perform an HA installation. Please add one more to proceed.""" click.echo(min_masters_message) elif len(masters) >= 3: ha_message = """ NOTE: Multiple masters specified, this will be an HA deployment with a separate etcd cluster. You will be prompted to provide the FQDN of a load balancer and a host for storage once finished entering hosts. """ click.echo(ha_message) dedicated_nodes_message = """ WARNING: Dedicated nodes are recommended for an HA deployment. If no dedicated nodes are specified, each configured master will be marked as a schedulable node.""" min_ha_nodes_message = """ WARNING: A minimum of 3 dedicated nodes are recommended for an HA deployment.""" if len(dedicated_nodes) == 0: click.echo(dedicated_nodes_message) elif len(dedicated_nodes) < 3: click.echo(min_ha_nodes_message) click.echo('')
Example #30
Source File: cli_installer.py From origin-ci-tool with Apache License 2.0 | 4 votes |
def check_hosts_config(oo_cfg, unattended): click.clear() masters = [host for host in oo_cfg.deployment.hosts if host.is_master()] if len(masters) == 2: click.echo("A minimum of 3 masters are required for HA deployments.") sys.exit(1) if len(masters) > 1: master_lb = [host for host in oo_cfg.deployment.hosts if host.is_master_lb()] if len(master_lb) > 1: click.echo('ERROR: More than one master load balancer specified. Only one is allowed.') sys.exit(1) elif len(master_lb) == 1: if master_lb[0].is_master() or master_lb[0].is_node(): click.echo('ERROR: The master load balancer is configured as a master or node. ' 'Please correct this.') sys.exit(1) else: message = """ ERROR: No master load balancer specified in config. You must provide the FQDN of a load balancer to balance the API (port 8443) on all master hosts. https://docs.openshift.org/latest/install_config/install/advanced_install.html#multiple-masters """ click.echo(message) sys.exit(1) dedicated_nodes = [host for host in oo_cfg.deployment.hosts if host.is_node() and not host.is_master()] if len(dedicated_nodes) == 0: message = """ WARNING: No dedicated nodes specified. By default, colocated masters have their nodes set to unschedulable. If you proceed all nodes will be labelled as schedulable. """ if unattended: click.echo(message) else: confirm_continue(message) return