def country(country, chart, hist, type): """Get data of a specific country.""" worldwide_table = PrettyTable() worldwide_table.field_names = [ color.prCyan('Country'), color.prCyan('Total Cases'), color.prCyan('Today Cases'), color.prRed('Total Deaths'), color.prRed('Today Deaths'), color.prGreen('Recovered Cases'), color.prYellow("Excluded cases"), color.prPurple("Critical") ] with yaspin(text="Civid-19 Cases Of " + country, color="cyan") as sp: data, meta_data = get_country.get_country(country) worldwide_table.add_row(data) time.sleep(1) click.echo(worldwide_table) print(' ') if chart: labels = ['Total Cases', 'Total Deaths', 'Recovered Cases'] data_chart = [data[1], data[3], data[5]] data_chart = [[int(i)] for i in data_chart] args = {'stacked': False, 'width': 100, 'no_labels': False, 'format': '{:,}', 'suffix': '', "vertical": False} tg.chart(colors=[91, 94], data=data_chart, args=args, labels=labels) if hist: country_full_name = data[0] with yaspin(text="Drawing a histogram of " + country, color="cyan") as sp: # Handle ISO-code as country name by using country name from meta-info of countries endpoint labels_hist, hist_data = get_country.get_country_hist(country_full_name, type) time.sleep(1) args = {'stacked': False, 'width': 100, 'no_labels': False, 'format': '{:,}', 'suffix': '', "vertical": False} click.secho("Civid-19 '" + type + "' for last 20 day in " + country_full_name + ".", bg='black', fg='yellow', blink=True, bold=True) try: tg.chart(colors=[91, 94], data=hist_data, args=args, labels=labels_hist) except IndexError: click.secho("No historical data found in " + country + ".", bg='black', fg='red', bold=True)
def all_colors(): with yaspin(text="Colors!").bouncingBar as sp: time.sleep(2) colors = ("red", "green", "yellow", "blue", "magenta", "cyan", "white") for color in colors: sp.color, sp.text = color, color time.sleep(2)
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 add(name): value = click.prompt(f"Value for variable {name}?") with yaspin(Spinners.aesthetic, text=f"Adding variable {name}", color="yellow") as spinner: response = helpers.add_variable(name, value) create_variables_file(utilities.get_active_project()[ 'name'], utilities.get_active_project()['id']) spinner.text = "" spinner.ok(f"🥞 added variable {name}")
def wrapper(*args, **kwargs): with yaspin(spinner=Spinners.line): account = self.login_user() if not account: return if with_account: kwargs['account'] = account fn(*args, **kwargs)
def init_skale(endpoint, wallet=None, disable_spin=DISABLE_SPIN): """Init read-only instance of SKALE Allocator library""" if disable_spin: return SkaleAllocator(endpoint, SKALE_ALLOCATOR_ABI_FILE, wallet) with yaspin(text="Loading", color=SPIN_COLOR) as sp: sp.text = 'Connecting to SKALE Allocator contracts' skale = SkaleAllocator(endpoint, SKALE_ALLOCATOR_ABI_FILE, wallet) return skale
def custom_signal_handler(): def my_handler(signum, frame, spinner): spinner.red.fail("[Received SIGINT]") spinner.stop() sys.exit(0) with yaspin(sigmap={signal.SIGINT: my_handler}, text=DEFAULT_TEXT): time.sleep(5)
def init_skale(endpoint, wallet=None, spin=True): """Init read-only instance of SKALE library""" if not spin: return Skale(endpoint, SKALE_VAL_ABI_FILE, wallet) with yaspin(text="Loading", color=SPIN_COLOR) as sp: sp.text = 'Connecting to SKALE Manager contracts' skale = Skale(endpoint, SKALE_VAL_ABI_FILE, wallet) return skale
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 revoke(view): with yaspin( text="Revoking nested authorized view permissions for view '{}'".format(view), color="yellow", ): view.revoke_permissions() formatted_tree = view.format_tree(show_status=True) print(formatted_tree)
def test_timer_idle(): sp = yaspin(timer=True) assert sp.elapsed_time == 0 sp._freeze("") assert "(0:00:00.00)" in sp._last_frame
def add(name): with yaspin(Spinners.aesthetic, text=f"Adding endpoint {name}", color="yellow") as spinner: response = helpers.add_endpoint(name) spinner.text = "" spinner.ok(f"🥞 added endpoint {name}")
def loadautoskip(lang): ''' Loads autoskip of lang (param) to autoskip (global) Depends on global variables: autoskip :param lang: Sign language to get autoskip for. :returns: Nothing. ''' global autoskip reallang = "english" if lang == "dgs": reallang = "german" if not os.path.isfile('Data_TxtToSL/autoskip/{}.txt'.format(reallang)): with yaspin(text="Downloading 'Data_TxtToSL/autoskip/{}.txt'".format( reallang)) as sp1: r = requests.get( "https://oojmed.com/Data_TxtToSL/autoskip/{}.txt".format( reallang)) if r.status_code == 200: with open('Data_TxtToSL/autoskip/{}.txt'.format(reallang), 'wb') as f: f.write(r.content) sp1.ok(ansi.GREEN + "✓" + ansi.END) else: sp1.fail(ansi.RED + "✗" + ansi.END) with yaspin(text="Loading phrases from 'Data_TxtToSL/autoskip/{}.txt'". format(reallang)) as sp2: autoskip = [] with open('Data_TxtToSL/autoskip/{}.txt'.format(reallang), 'r') as f: autoskip = f.readlines() autoskip = [word.strip() for word in autoskip] sp2.ok(ansi.GREEN + "✓" + ansi.END) print() for word in autoskip: print(word)
def __add_gpm_thumbs_up_to_spotify(spot_client: spotipy.Spotify) -> None: with yaspin(text='Getting Spotify track IDs...', color='yellow') as spinner: fave_track_ids = __get_playlist_track_ids(spot_client, 'gpm_thumbs_up') spinner.ok('✅ ') with yaspin(text='Adding favorites...', color='yellow') as spinner: for track_id in fave_track_ids: fave_added = add_track_to_favorites(spot_client, track_id) retries = 0 while not fave_added and retries < 3: spot_client: spotipy.Spotify = get_spot_client() fave_added = add_track_to_favorites(spot_client, track_id) retries += 1 if retries == 3: break spinner.ok('✅ ')
def extract( ctx: click.Context, state: State, image_id: Optional[int], movie_id: Optional[int], path: Optional[Path], with_drawing: bool, **kwargs, ) -> None: """Extract keypoints from image or movie. Either '--image-id' or '--movie-id' or '--path' is required. When using the '--with-drawing' option, you can use drawing options such as '--rule', '--bg-rule', and '--rule-file', and '--download / --no-download'. In addition, when downloading the drawn file, you can use download options such as '-o, --out', '--force' and '--open / --no-open'. """ required_options = [image_id, movie_id, path] if required_options.count(None) != len(required_options) - 1: raise click.UsageError( "Either '--image-id' or '--movie-id' or '--path' is required" ) if not with_drawing: args = click.get_os_args() options = check_draw_options(args) + check_download_options(args) echo_invalid_option_warning("using '--with-drawing'", options) client = get_client(state) result = None if path is not None: result = ctx.invoke(upload, path=path)._asdict() echo() data = result or {"image_id": image_id, "movie_id": movie_id} try: keypoint_id = client.extract_keypoint(data=data) echo(f"Keypoint extraction started. (keypoint id: {color_id(keypoint_id)})") if state.use_spinner: with yaspin(text="Processing..."): response = client.wait_for_extraction(keypoint_id) else: response = client.wait_for_extraction(keypoint_id) except RequestsError as e: raise ClickException(str(e)) if response.status == "SUCCESS": echo_success("Keypoint extraction is complete.") elif response.status == "TIMEOUT": raise ClickException("Keypoint extraction is timed out.") else: raise ClickException(f"Keypoint extraction failed.\n{response.failure_detail}") if with_drawing: echo() ctx.invoke(draw, keypoint_id=keypoint_id, **kwargs)
def main(): with yaspin(text="Right spinner", side="right", color="cyan") as sp: time.sleep(2) # Switch to left spinner sp.side = "left" # or just ``sp.left`` sp.text = "Left spinner" time.sleep(2)
def main(): names = [ attr for attr in dir(Spinners) if not callable(getattr(Spinners, attr)) if not attr.startswith("_") ] for name in sorted(names): spinner = getattr(Spinners, name) with yaspin(spinner, text=name): time.sleep(3)
def main(): with yaspin(text="Right spinner", right=True) as sp: time.sleep(2) # Switch to left spinner sp.right = False sp.text = "Left spinner" time.sleep(2)
def wait_for_files(label, fnames): with yaspin(Spinners.clock, text=f"elapsed time: {label}", timer=True) as sp: while True: all_exists = all(bool(glob(fn)) for fn in fnames) if all_exists: break sleep(10) sp.ok("✅")
def ball(): # Set with arguments with yaspin( color="white", on_color="on_magenta", attrs=["dark", "blink", "concealed"], ).bouncingBall as sp: sp.text = "Dark blink concealed white ball on magenta color" time.sleep(5)
def connect(self): # TODO: Find networks with the best signal, and connect to that one only. log("Magically connecting to the best network...", "yellow") with yaspin(): self.wireless.connect(self.ssid) # TODO: Ping some endpoint until connectivity is guaranteed? log("You're connected! Enjoy your magic internet.")
def test_side(side, expected): sp = yaspin() if isinstance(expected, Exception): with pytest.raises(AttributeError): getattr(sp, side) else: getattr(sp, side) assert sp.side == expected
def test_hide_show(capsys, text, request): # Setup sp = yaspin() sp.start() # Ensure that sp.stop() will be executed def teardown(): sp.stop() request.addfinalizer(teardown) # # Actual test # sp.hide() # ensure that hidden spinner flag was set assert sp._hide_spin.is_set() out, _ = capsys.readouterr() # ensure that text was cleared with the hide method assert out[-4:] == "\r\033[K" # properly encode text to unicode if running in PY2 if PY2: text = to_unicode(text).encode(ENCODING) # ``\n`` is required to flush stdout during # the hidden state of the spinner sys.stdout.write("{0}\n".format(text)) out, _ = capsys.readouterr() # cleans stdout from _clear_line and \r out = out.replace("\r\033[K", "") # handle out and text encodings (come out messy in PY2) # Under PY2 ``capsys.readouterr`` always produces ``out`` # of type ``unicode``. Conversion to bytes is required # for proper ``out`` and ``text`` comparison. if PY2: out = out.encode(ENCODING) if isinstance(text, str): text = text.encode(ENCODING) assert isinstance(out, basestring) assert out[-1] == "\n" if text: assert out[:-1] == text sp.show() # ensure that hidden spinner flag was cleared assert not sp._hide_spin.is_set() out, _ = capsys.readouterr() # ensure that text was cleared before resuming the spinner assert out[:4] == "\r\033[K"
def right_spinner(): with yaspin(text="Right spinner", right=True, color="cyan") as sp: time.sleep(2) # Switch to left spinner sp.right = False sp.text = "Left spinner" time.sleep(2)
def right_spinner(sleep=2): with yaspin(text="Right spinner", side="right", color="cyan") as sp: time.sleep(sleep) # Switch to left spinner sp.side = "left" sp.text = "Left spinner" time.sleep(sleep)
def context_mngr_setup(): with yaspin(Spinners.noise, text="Noise spinner") as swirl: time.sleep(2) swirl.spinner = Spinners.simpleDotsScrolling swirl.text = "Scrolling Dots spinner" swirl.color = "magenta" time.sleep(2)
def upload_assets(self, tag_name: str, files: List[str]) -> None: """ Upload assets to a specified release Github API: POST :server/repos/:owner/:repo/releases/:release_id/assets{?name,label}""" if len(files) > MAX_UPLOAD: raise ArgumentError( "cannot upload more than {} files".format(MAX_UPLOAD)) with yaspin(text="Checking release for tag {}".format( tag_name)) as spinner: upload_url = self._get_release_upload_url(tag_name) if not upload_url: raise ArgumentError( "Could not get the upload URL or the release with tag {} does not exist" .format(tag_name)) spinner.ok() headers = { "Content-type": "application/octet-stream", } with yaspin(text="Uploading asset") as spinner: for file in files: abspath = path.abspath(file) filename = path.basename(abspath) url = "{}?name={}".format(upload_url, filename) spinner.write("Uploading '{}' to '{}/{}/{}'".format( abspath, self._account, self._repository, tag_name)) with open(abspath, "rb") as f: file_data = f.read() response = requests.post(url, data=file_data, headers=headers, auth=self.auth) if response.status_code != HTTPStatus.CREATED: spinner.fail() raise UploadError("Could not upload the file") spinner.write("Upload complete") spinner.ok()
def _start_watch_mode(self, args: ConvertModeArguments) -> None: """Starts and runs the watch mode until canceled Arguments: args {ConvertModeArguments} -- The arguments for convert mode """ # Use custom event handler event_handler = self._create_watch_handler( args['in_path'], args['out_path'], ) # Init the observer observer = Observer() observer.schedule(event_handler, args['in_path'], recursive=True) self._logger.debug(f"Starting watch mode for: {args['in_path']}") if self._visual: print( colored('Starting watcher for:', 'blue', attrs=['bold']), colored(f"{os.path.abspath(args['in_path'])}", 'blue'), ) else: self._logger.info(f"Starting watch mode for: {args['in_path']}") # Start observer.start() # Keep the process running while # the watcher watches (until KeyboardInterrupt) try: while True: # Pretty spinner =) spinner_text = colored( 'Watching files', 'blue', ) + colored(' (use Ctrl+c to exit)', 'red') with yaspin( Spinners.bouncingBar, text=spinner_text, color='blue', ): time.sleep(1) except KeyboardInterrupt: self._logger.debug('Got a KeyboardInterrupt, stopping watcher.') observer.stop() observer.join() self._logger.debug(f"Stoped watching {args['in_path']}") if self._visual: print( colored('Stoped watcher for:', 'blue', attrs=['bold']), colored(f"{os.path.abspath(args['in_path'])}", 'blue'), ) else: self._logger.info(f"Stoped watching {args['in_path']}")
async def task2(*, desc=None): from yaspin import yaspin with yaspin(text="Colors!") as sp: # Support all basic termcolor text colors colors = ("red", "green", "yellow", "blue", "magenta", "cyan", "white") for color in colors: sp.color, sp.text = color, color await asyncio.sleep(1)
def reversed_spinner(sleep=1): with yaspin(text="Reversed spinner", reversal=True, color="cyan") as sp: time.sleep(sleep) sp.spinner = Spinners.line time.sleep(sleep) sp.text = "Enjoy!" sp.ok("☀️ ")
def test_timer_rounding_up(): sp = yaspin(timer=True) sp.start() sp.stop() sp._stop_time = sp._start_time + 0.996 sp._freeze("") assert "(0:00:01.00)" in sp._last_frame
def main(): from cob.cli.docker_cli import _build_cob_sdist tmpdir = pathlib.Path(tempfile.mkdtemp()) sdist_file = tmpdir / 'cob_sdist.tar.gz' logbook.StderrHandler(level=logbook.DEBUG).push_application() _build_cob_sdist(sdist_file) os.environ['COB_SDIST_FILENAME'] = str(sdist_file) projects = [] processes = [] logs = [] project_names = set() for project_dir in _ROOT.iterdir(): proj_yaml = project_dir / '.cob-project.yml' if proj_yaml.exists(): with proj_yaml.open() as f: name = yaml.load(f.read()).get('name') if name is None: sys.exit(f'Project {project_dir.stem} does not have a name configured') if name in project_names: sys.exit(f'Project name {name} is already in use (found in {project_dir})') project_names.add(name) projects.append(proj_yaml) for proj_yaml in projects: project_dir = proj_yaml.parent log = tmpdir / project_dir.stem logs.append(log) with log.open('w') as logfile: _logger.info('Building {}...', project_dir) processes.append( subprocess.Popen(f'{sys.executable} -m cob.cli.main docker build', cwd=project_dir, stderr=subprocess.STDOUT, stdout=logfile, shell=True) ) success = True with yaspin(text='Waiting for projects to build'): for p, log in zip(processes, logs): project = log.stem result = p.wait() if result != 0: success = False click.echo(click.style(f'Build failed for {project}. More details below', fg='red')) with log.open() as f: for line in f: click.echo(click.style(line, fg='yellow')) click.echo(click.style('^' * 80, fg='red')) if not success: raise click.ClickException('Some build processes failed')
def _execute_long_command(cmd, message): from yaspin import yaspin with tempfile.NamedTemporaryFile(delete=False) as fp_out, \ tempfile.NamedTemporaryFile(delete=False) as fp_err, \ subprocess.Popen(cmd, stdout=fp_out, stderr=fp_err) as proc, \ yaspin(text=message) as spinner: _logger.trace(message) retcode = proc.wait() if retcode != 0: spinner.fail() fp_err.flush() fp_err.seek(0) for line in fp_err: click.echo(click.style(line.decode('utf8'), fg='red'), file=sys.stderr) raise click.ClickException(_LONG_EXECUTION_ERROR.format(rc=retcode, cmd=' '.join(cmd).strip(), stdout=fp_out.name, stderr=fp_err.name)) spinner.ok()
import time from random import randint from yaspin import yaspin with yaspin(text="Loading", color="yellow") as spinner: time.sleep(2) # time consuming code success = randint(0, 1) if success: spinner.ok("✅ ") else: spinner.fail("💥 ")
import time from yaspin import yaspin with yaspin(text="Colors!") as sp: # Support all basic termcolor text colors colors = ("red", "green", "yellow", "blue", "magenta", "cyan", "white") for color in colors: sp.color, sp.text = color, color time.sleep(1)
import time from yaspin import yaspin from yaspin.spinners import Spinners with yaspin(Spinners.earth, text="Earth") as sp: time.sleep(2) # time consuming code # change spinner sp.spinner = Spinners.moon sp.text = "Moon" time.sleep(2)
import time from yaspin import yaspin # Context manager: with yaspin(): time.sleep(3) # time consuming code # Function decorator: @yaspin(text="Loading...") def some_operations(): time.sleep(3) # time consuming code some_operations()
import time from yaspin import yaspin with yaspin().white.bold.shark.on_blue as sp: sp.text = "White bold shark in a blue sea" time.sleep(5)