def cmd_delete(self, uuid, force=False, skip_query=False): try: if not skip_query: try: with Spinner(text=f"Querying by {self.resource_uuid_name} {uuid}"): response = self.get_client_resource().get_by_uuid(uuid=uuid) except CloudscaleApiException as e: results = self.cmd_get_by_name(name=uuid) if not results: if self.resource_name_key: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name} or {self.resource_name_key}: {uuid}" else: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name}: {uuid}" click.echo(msg, err=True) sys.exit(1) if len(results) > 1: click.echo(f"Error: More than one resource found for {self.cloud_resource_name} having name: {uuid}", err=True) sys.exit(1) # Single resource found, remember identifier response = results[0] uuid = results[0]['href'].split('/')[-1] click.echo(self._format_output(response)) if not force: click.confirm('Do you want to delete?', abort=True) with Spinner(text=f"Deleting by {self.resource_uuid_name} {uuid}"): self.get_client_resource().delete(uuid) click.echo(f"{uuid} deleted!") except Exception as e: click.echo(e, err=True) sys.exit(1)
def http_get(self, url): # http 'GET' # set spinner if url.find('surf-forecast') is not -1: self.loader = yaspin(Spinner(Spinners.shark, 100)).white.bold.on_blue else: self.loader = yaspin(Spinner(Spinners.earth, 180)) # start loader to anticipate a possible slow request self.loader.start() try: with closing(get(url, stream=True)) as resp: if self.is_good_response(resp): self.loader.stop() # stop loader return resp.content else: self.loader.stop() # stop loader return None except RequestException as e: self.log_error('Error during requests to {0} : {1}'.format( url, str(e))) self.loader.stop() # stop loader return None
def cmd_update(self, uuid, tags=None, clear_tags=None, clear_all_tags=False, wait=False, **kwargs): try: with Spinner(text=f"Querying by {self.resource_uuid_name} {uuid}"): self.get_client_resource().get_by_uuid(uuid=uuid) except CloudscaleApiException as e: results = self.cmd_get_by_name(name=uuid) if not results: if self.resource_name_key: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name} or {self.resource_name_key}: {uuid}" else: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name}: {uuid}" click.echo(msg, err=True) sys.exit(1) if len(results) > 1: click.echo(f"Error: More than one resource found for {self.cloud_resource_name} having name: {uuid}. Please use {self.resource_uuid_name} to select the resource.", err=True) sys.exit(1) # Single resource found, remember identifier uuid = results[0]['href'].split('/')[-1] try: with Spinner(text=f"Processing tags"): if any([clear_all_tags, tags, clear_tags]): _tags = dict() if not clear_all_tags: response = self.get_client_resource().get_by_uuid(uuid=uuid) _tags = response.get('tags', dict()).copy() for k in clear_tags: _tags.pop(k, None) if tags: try: _tags.update(tags_to_dict(tags)) except ValueError as e: click.echo(e, err=True) sys.exit(1) else: _tags = None with Spinner(text=f"Updating by {self.resource_uuid_name} {uuid}"): self.get_client_resource().update( uuid=uuid, tags=_tags, **kwargs, ) if wait: response = self.wait_for_status(uuid=uuid) else: with Spinner(text=f"Querying {uuid}"): response = self.get_client_resource().get_by_uuid(uuid=uuid) click.echo(self._format_output(response)) except Exception as e: click.echo(e, err=True) sys.exit(1)
def test_out_converted_to_builtin_str(text, frames, interval, reversal, side): sp = Spinner(frames, interval) sp = yaspin(sp, text, side=side, reversal=reversal) for _ in range(len(frames)): frame = next(sp._cycle) out = sp._compose_out(frame) assert isinstance(out, builtin_str)
def cmd_list(self, filter_tag=None, filter_json=None, action=None, delete=False, force=False, wait=False): if action and delete: click.echo("Error: --action and --delete are mutually exclusive", err=True) sys.exit(1) try: with Spinner(text="Querying"): response = self.get_client_resource().get_all(filter_tag=filter_tag) if filter_json: try: response = jmespath.search(filter_json, response) except Exception as e: click.echo(f"filter_json error: {e}", err=True) sys.exit(1) if response: click.echo(self._format_output(response)) if delete: if not force: click.confirm(f"Do you want to delete?", abort=True) for r in response: if 'href' not in r: click.echo("No href found, could not delete.", err=True) sys.exit(1) uuid = r['href'].split('/')[-1] self.cmd_delete(uuid=uuid, force=True, skip_query=True) elif action: if not force: click.confirm(f"Do you want to {action}?", abort=True) for r in response: if 'href' not in r: click.echo(f"No href found, could not {action}.", err=True) sys.exit(1) uuid = r['href'].split('/')[-1] with Spinner(text=f"{action.capitalize()} {uuid}"): getattr(self.get_client_resource(), action)(uuid) if wait: response = self.get_client_resource().get_all(filter_tag=filter_tag) for r in response: uuid = r['href'].split('/')[-1] self.wait_for_status(uuid=uuid) with Spinner(text="Querying"): response = self.get_client_resource().get_all(filter_tag=filter_tag) click.echo(self._format_output(response)) except Exception as e: click.echo(e, err=True) sys.exit(1)
def spinner(text: str = ""): try: from yaspin import yaspin, Spinner have_yaspin = True except ImportError: have_yaspin = False if not have_yaspin: return _NullSpinner() console = Console._get_console() if console._use_spinner: theme = Console._get_theme() frames, delay = theme.get_frames(width=console.width - len(text) - 10) sp = Spinner(frames, delay) y = yaspin(sp, text=text, side="right") y.success = lambda: theme.spinner_success(y) y.failure = lambda: theme.spinner_failure(y) return y else: return _NullSpinner()
def test_spinner_getter(frames, interval): sp = yaspin() assert sp.spinner == default_spinner new_spinner = Spinner(frames, interval) sp.spinner = new_spinner assert sp.spinner == sp._set_spinner(new_spinner)
def test_spinner_getter(frames, interval): swirl = yaspin() assert swirl.spinner == default_spinner new_spinner = Spinner(frames, interval) swirl.spinner = new_spinner assert swirl.spinner == swirl._set_spinner(new_spinner)
def test_out_converted_to_builtin_str(text, frames, interval, right, reverse): sp = Spinner(frames, interval) swirl = yaspin(sp, text, right=right, reverse=reverse) for _ in range(len(frames)): frame = next(swirl._cycle) out = swirl._compose_out(frame) assert isinstance(out, builtin_str)
def test_input_converted_to_unicode(text, frames, interval, right, reverse): sp = Spinner(frames, interval) swirl = yaspin(sp, text, right=right, reverse=reverse) if isinstance(swirl._frames, basestring): assert isinstance(swirl._frames, str) if isinstance(swirl._frames, (list, tuple)): assert isinstance(swirl._frames[0], str) assert isinstance(swirl._text, str)
def test_input_converted_to_unicode(text, frames, interval, reversal, side): sp = Spinner(frames, interval) sp = yaspin(sp, text, side=side, reversal=reversal) if isinstance(sp._frames, basestring): assert isinstance(sp._frames, str) if isinstance(sp._frames, (list, tuple)): assert isinstance(sp._frames[0], str) assert isinstance(sp._text, str)
def terminal_spinner(*args, **kw): nonlocal on_success nonlocal on_failure nonlocal options text_to_display: str color: str if "text" not in kw.keys(): text_to_display = choice(options) else: text_to_display = kw["text"] if "color" not in kw.keys(): color = "red" else: color = kw["color"] sp = Spinner(["🌌", "🚀", "🌌"], 100) with yaspin(sp, text=text_to_display, color=color) as sp: some_result: Optional[any] try: some_result = function(*args, **kw) sp.write(hype_str(f"{on_success} The task was successful.\n")) return some_result except Exception as e: sp.write(on_failure + " could not be completed.") raise (e)
def cmd_get_by_name(self, name): results = [] if not self.resource_name_key: return results with Spinner(text=f"Querying by {self.resource_name_key} {name}"): responses = self.get_client_resource().get_all() for response in responses: if self.resource_name_key not in response: break if response.get(self.resource_name_key) == name: results.append(response) return results
def cmd_act(self, action, uuid, wait=False): with Spinner(text=f"Processing"): try: with Spinner(text=f"Querying by {self.resource_uuid_name} {uuid}"): self.get_client_resource().get_by_uuid(uuid=uuid) except CloudscaleApiException as e: results = self.cmd_get_by_name(name=uuid) if not results: if self.resource_name_key: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name} or {self.resource_name_key}: {uuid}" else: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name}: {uuid}" click.echo(msg, err=True) sys.exit(1) if len(results) > 1: click.echo(f"Error: More than one resource found for {self.cloud_resource_name} having name: {uuid}. Please use {self.resource_uuid_name} to select the resource.", err=True) sys.exit(1) # Single resource found, remember identifier uuid = results[0]['href'].split('/')[-1] try: with Spinner(text=f"{action} {uuid}"): getattr(self.get_client_resource(), action)(uuid) if wait: response = self.wait_for_status(uuid=uuid) else: with Spinner(text=f"Querying {uuid}"): response = self.get_client_resource().get_by_uuid(uuid=uuid) click.echo(self._format_output(response)) except Exception as e: click.echo(e, err=True) sys.exit(1)
def cmd_create(self, silent=False, **kwargs): try: if 'tags' in kwargs: kwargs['tags'] = self._handle_tags(kwargs['tags']) name = kwargs.get(self.resource_name_key, '') with Spinner(text=f"Creating {name}"): response = self.get_client_resource().create(**kwargs) if not silent: click.echo(self._format_output(response)) else: return response except Exception as e: click.echo(e, err=True) sys.exit(1)
def cli(files, output, halign, valign, margin, font, size, start, merge, blank): """ тнРя╕П Add pages to PDFs and merge(optional) -> PERFECT DOCUMENT! ЁЯУС""" file_paths = [os.path.join(cwd, file) for file in files] output_paths = [] for path in file_paths: root, ext = os.path.splitext(path) output_paths.append(root + PDF2DOC_SUFFIX + ext) output_writers = paged_pdfs_writer(files=file_paths, h_align=halign, v_align=valign, margin=Margin(all=margin), font=font, font_size=size, format=PDF2DOC_FORMAT, add_blank=blank, start_num=start) sp = Spinner([ ' таЛ', ' таЩ', ' та╣', ' та╕', ' та╝', ' та┤', ' таж', ' таз', ' таЗ', ' таП' ], 100) with yaspin(sp, text="Saving") as spinner: for writer, path in zip(output_writers, output_paths): with open(path, 'wb') as f: writer.write(f) spinner.text = "Saving [Success]" spinner.ok(" тЬЕ") if merge: with yaspin(sp, text="Marging") as spinner: merger = concat_pdfs_merger(output_paths) merger.write(output) merger.close() for path in output_paths: send2trash(path) spinner.text = "Marging [Success]" spinner.ok(" тЬЕ") echo('') echo( crayons.yellow(' тнРя╕ПтнРя╕ПтнРя╕П All Done! тнРтнРя╕ПтнРя╕Пя╕П', bold=True))
def wait_for_status(self, uuid, status = "changing", max_sleep = 4, retries = 30, path = ""): with Spinner(text=f"Waiting for status {uuid}: ...") as sp: for retry in range(0, retries): response = self.get_client_resource().get_by_uuid(uuid=uuid, path=path) if response['status'] != status: break sp.text = f"Waiting for {uuid} to finish, current status: {response['status']} { retry * '.'}" # Exponential wait... sleep = 2 ** retry if sleep > max_sleep: sleep = max_sleep time.sleep(sleep) else: sp.text = f"Waiting for status {uuid} timed out." time.sleep(1) return response
def cmd_show(self, uuid): try: with Spinner(text=f"Querying by {self.resource_uuid_name} {uuid}"): response = self.get_client_resource().get_by_uuid(uuid=uuid) click.echo(self._format_output(response)) except CloudscaleApiException as e: results = self.cmd_get_by_name(name=uuid) if not results: if self.resource_name_key: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name} or {self.resource_name_key}: {uuid}" else: msg = f"No resource found for {self.cloud_resource_name} having {self.resource_uuid_name}: {uuid}" click.echo(msg, err=True) sys.exit(1) click.echo(self._format_output(results)) except Exception as e: click.echo(e, err=True) sys.exit(1)
def test_spinner_setter(frames, interval): sp = yaspin() assert sp._spinner == default_spinner assert isinstance(sp._frames, str) assert sp._interval == sp._spinner.interval * 0.001 assert isinstance(repr(sp), builtin_str) new_spinner = Spinner(frames, interval) sp.spinner = new_spinner assert sp._spinner == sp._set_spinner(new_spinner) if isinstance(sp._frames, basestring): assert isinstance(sp._frames, str) if isinstance(sp._frames, (list, tuple)): assert isinstance(sp._frames[0], str) assert sp._interval == sp._spinner.interval * 0.001 assert isinstance(repr(sp), builtin_str)
def submit(json_option, pipeline_path, runtime_config_name, monitor_option, timeout_option): """ Submit a pipeline to be executed on the server """ click.echo() print_banner("Elyra Pipeline Submission") runtime_config = _get_runtime_config(runtime_config_name) runtime_schema = runtime_config.schema_name pipeline_definition = _preprocess_pipeline( pipeline_path, runtime=runtime_schema, runtime_config=runtime_config_name ) pipeline_runtime_type = _get_pipeline_runtime_type(pipeline_definition) if pipeline_runtime_type: _build_component_cache() try: _validate_pipeline_definition(pipeline_definition) except Exception: raise click.ClickException("Pipeline validation FAILED. The pipeline was not submitted for execution.") with Spinner(text="Submitting pipeline..."): response: PipelineProcessorResponse = _execute_pipeline(pipeline_definition) if not json_option: if response: msg = [] # If there's a git_url attr, assume Apache Airflow DAG repo. # TODO: this will need to be revisited once front-end is decoupled from runtime platforms. if hasattr(response, "git_url"): msg.append(f"Apache Airflow DAG has been pushed to: {response.git_url}") msg.extend( [ f"Check the status of your job at: {response.run_url}", f"The results and outputs are in the {response.object_storage_path} ", f"working directory in {response.object_storage_url}", ] ) print_info("Job submission succeeded", msg) click.echo() print_banner("Elyra Pipeline Submission Complete") else: if response: click.echo() print(json.dumps(response.to_json(), indent=4)) # Start pipeline run monitoring, if requested if runtime_schema == "kfp" and monitor_option: minute_str = "minutes" if timeout_option > 1 else "minute" try: msg = ( f"Monitoring status of pipeline run '{response.run_id}' for up to " f"{timeout_option} {minute_str}..." ) with Spinner(text=msg): status = _monitor_kfp_submission(runtime_config, runtime_config_name, response.run_id, timeout_option) except TimeoutError: click.echo( "Monitoring was stopped because the timeout threshold " f"({timeout_option} {minute_str}) was exceeded. The pipeline is still running." ) sys.exit(EXIT_TIMEDOUT) else: # The following are known KFP states: 'succeeded', 'failed', 'skipped', # 'error'. Treat 'unknown' as error. Exit with appropriate status code. click.echo(f"Monitoring ended with run status: {status}") if status.lower() not in ["succeeded", "skipped"]: # Click appears to use non-zero exit codes 1 (ClickException) # and 2 (UsageError). Terminate. sys.exit(click.ClickException.exit_code)
def _build_component_cache(): """Initialize a ComponentCache instance and wait for it to complete all tasks""" with Spinner(text="Initializing the component cache..."): component_cache = ComponentCache.instance(emulate_server_app=True) component_cache.load() component_cache.wait_for_all_cache_tasks()
def __init__(self, proxy): self.url = "http://pwndb2am4tzkvold.onion/" self.session = requests.session() self.__set_proxies(proxy) self.parser = Parser() self.spinner = Spinner(["[ ]", "[.]", "[:]", "[.]", "[ ]"], 200)
from colorama import Fore, Style from typing import List from yaspin import Spinner INTERVAL = 80 OPEN = f'{Style.BRIGHT}' CLOSE = f'{Style.RESET_ALL}' COLORS = (Fore.GREEN, Fore.BLUE, Fore.MAGENTA, Fore.RED, Fore.YELLOW) frames: List[str] = [] for color in COLORS: frames += ( f'{OPEN}{color}=> {CLOSE}', f'{OPEN}{color}==> {CLOSE}', f'{OPEN}{color}===>{CLOSE}', f'{OPEN}{color} ==={CLOSE}', f'{OPEN}{color} =={CLOSE}', f'{OPEN}{color} ={CLOSE}', f'{OPEN}{color} <{CLOSE}', f'{OPEN}{color} <={CLOSE}', f'{OPEN}{color} <=={CLOSE}', f'{OPEN}{color}<==={CLOSE}', f'{OPEN}{color}=== {CLOSE}', f'{OPEN}{color}== {CLOSE}', f'{OPEN}{color}= {CLOSE}', f'{OPEN}{color} {CLOSE}', f'{OPEN}{color}> {CLOSE}', ) spin = Spinner(frames, INTERVAL)
def context_manager_line(): line_spinner = Spinner("-\\|/", 150) with yaspin(line_spinner, "line"): time.sleep(3)
def export(pipeline_path, runtime_config, output, overwrite): """ Export a pipeline to a runtime-specific format """ click.echo() print_banner("Elyra pipeline export") rtc = _get_runtime_config(runtime_config) runtime_schema = rtc.schema_name runtime_type = rtc.metadata.get("runtime_type") pipeline_definition = _preprocess_pipeline(pipeline_path, runtime=runtime_schema, runtime_config=runtime_config) # Verify that the pipeline's runtime type is compatible with the # runtime configuration pipeline_runtime_type = _get_pipeline_runtime_type(pipeline_definition) if pipeline_runtime_type and pipeline_runtime_type != "Generic" and pipeline_runtime_type != runtime_type: raise click.BadParameter( f"The runtime configuration type '{runtime_type}' does not match " f"the pipeline's runtime type '{pipeline_runtime_type}'.", param_hint="--runtime-config", ) resources = RuntimeTypeResources.get_instance_by_type(RuntimeProcessorType.get_instance_by_name(runtime_type)) supported_export_formats = resources.get_export_extensions() if len(supported_export_formats) == 0: raise click.ClickException(f"Runtime type '{runtime_type}' does not support export.") # If, in the future, a runtime supports multiple export output formats, # the user can choose one. For now, choose the only option. selected_export_format = supported_export_formats[0] selected_export_format_suffix = f".{selected_export_format}" # generate output file name from the user-provided input if output is None: # user did not specify an output; use current directory # and derive the file name from the pipeline file name output_path = Path.cwd() filename = f"{Path(pipeline_path).stem}{selected_export_format_suffix}" else: if output.suffix == selected_export_format_suffix: # user provided a file name output_path = output.parent filename = output.name else: # user provided a directory output_path = output filename = f"{Path(pipeline_path).stem}{selected_export_format_suffix}" output_file = output_path.resolve() / filename # verify that the output path meets the prerequisites if not output_file.parent.is_dir(): try: output_file.parent.mkdir(parents=True, exist_ok=True) except Exception as ex: raise click.BadParameter(f"Cannot create output directory: {ex}", param_hint="--output") # handle output overwrite if output_file.exists() and not overwrite: raise click.ClickException( f"Output file '{str(output_file)}' exists and " "option '--overwrite' was not specified." ) if pipeline_runtime_type: _build_component_cache() # validate the pipeline try: _validate_pipeline_definition(pipeline_definition) except Exception: raise click.ClickException("Pipeline validation FAILED. The pipeline was not exported.") with Spinner(text="Exporting pipeline ..."): try: # parse pipeline pipeline_object = PipelineParser().parse(pipeline_definition) # process pipeline with warnings.catch_warnings(): warnings.simplefilter("ignore") asyncio.get_event_loop().run_until_complete( PipelineProcessorManager.instance().export( pipeline_object, selected_export_format, str(output_file), True ) ) except ValueError as ve: raise click.ClickException(f"Error parsing pipeline: \n {ve}") except RuntimeError as re: raise click.ClickException(f"Error exporting pipeline: \n {re} \n {re.__cause__}") click.echo(f"Pipeline was exported to '{str(output_file)}'.")
from yaspin.signal_handlers import fancy_handler from yaspin.spinners import Spinners def context_manager_default(): with yaspin(text="Braille"): time.sleep(3) def context_manager_line(): line_spinner = Spinner("-\\|/", 150) with yaspin(line_spinner, "line"): time.sleep(3) @yaspin(Spinner("⢄⢂⢁⡁⡈⡐⡠", 80), text="Dots") def decorated_function(): time.sleep(3) def pre_setup_example(): swirl = yaspin( spinner=Spinners.simpleDotsScrolling, text="swirl", color="red", side="right", sigmap={signal.SIGINT: fancy_handler}, ) with swirl as sp: time.sleep(2)
from yaspin import Spinner, yaspin from yaspin.base_spinner import default_spinner @pytest.mark.parametrize("spinner, expected", [ # None (None, default_spinner), # hasattr(spinner, "frames") and not hasattr(spinner, "interval") (namedtuple('Spinner', "frames")("-\\|/"), default_spinner), # not hasattr(spinner, "frames") and hasattr(spinner, "interval") (namedtuple('Spinner', "interval")(42), default_spinner), # Both attrs, not set (Spinner("", 0), default_spinner), # Both attrs, not frames (Spinner("", 42), default_spinner), # Both attrs, not interval (Spinner("-\\|/", 0), default_spinner), # Both attrs, are set (Spinner("-\\|/", 42), Spinner("-\\|/", 42)), ]) def test_set_spinner(spinner, expected): swirl = yaspin(spinner) assert swirl.spinner == expected
from .utils import (extract_in_id, filter_output, print_json_data, print_right_shift, show) DISCOVERY_SPINNER = Spinner([ "[= ]", "[== ]", "[=== ]", "[==== ]", "[===== ]", "[ ===== ]", "[ ===== ]", "[ ===== ]", "[ =====]", "[ ====]", "[ ===]", "[ ==]", "[ =]", "[ ==]", "[ ===]", "[ ====]", "[ =====]", "[ ===== ]", "[ ===== ]", "[ ===== ]", "[===== ]", "[==== ]", "[=== ]", "[== ]" ], 80) class KeyFile(object):
def test_repr(text, frames, interval): sp = Spinner(frames, interval) sp = yaspin(sp, text) assert isinstance(repr(sp), builtin_str)
from selenium import webdriver from selenium.webdriver.common.keys import Keys from yaspin import yaspin, Spinner import getpass sp = Spinner( ["😸", "😹", "😺", "😻", "😼", "😽", "😾", "😿", "🙀"], 200) login = input("Enter fb email: ") passw = getpass.getpass("Enter fb password: "******"m_login_email") password = browser.find_element_by_id( "m_login_password") or browser.find_element_by_name("pass") email.send_keys(login) password.send_keys(passw, Keys.RETURN) key = input("Search key: ") import time time.sleep(1) browser.get(f'https://m.facebook.com/{key}/posts/') with yaspin(sp, text="Okno chrome musi być aktywne, patrz na nie!!!"): for _ in range(120): browser.execute_script( "window.scrollTo(0, document.body.scrollHeight);")