Ejemplo n.º 1
0
def test_spinner_update():
    time = 0.0

    def get_time():
        nonlocal time
        return time

    console = Console(width=20,
                      force_terminal=True,
                      get_time=get_time,
                      _environ={})
    console.begin_capture()
    spinner = Spinner("dots")
    console.print(spinner)

    rule = Rule("Bar")

    spinner.update(text=rule)
    time += 80 / 1000
    console.print(spinner)

    result = console.end_capture()
    print(repr(result))
    expected = "⠋\n⠙ \x1b[92m─\x1b[0m\n"
    assert result == expected
Ejemplo n.º 2
0
def test_spinner_update():
    time = 0.0

    def get_time():
        nonlocal time
        return time

    console = Console(width=20,
                      force_terminal=True,
                      get_time=get_time,
                      _environ={})
    console.begin_capture()
    spinner = Spinner("dots")
    console.print(spinner)

    spinner.update(text="Bar", style="green", speed=2)
    time += 80 / 1000
    console.print(spinner)

    spinner.update(text=Rule("Bar"))
    time += 80 / 1000
    console.print(spinner)

    result = console.end_capture()
    print(repr(result))
    expected = f"⠋\n\x1b[32m⠙\x1b[0m Bar\n\x1b[32m⠸\x1b[0m \x1b[92m────── \x1b[0mBar\x1b[92m ───────\x1b[0m\n"
    assert result == expected
Ejemplo n.º 3
0
def test_spinner_render():
    time = 0.0

    def get_time():
        nonlocal time
        return time

    console = Console(width=80,
                      color_system=None,
                      force_terminal=True,
                      get_time=get_time)
    console.begin_capture()
    spinner = Spinner("dots", "Foo")
    console.print(spinner)
    time += 80 / 1000
    console.print(spinner)
    result = console.end_capture()
    print(repr(result))
    expected = "⠋ Foo\n⠙ Foo\n"
    assert result == expected
Ejemplo n.º 4
0
    def _make_table(self, job: SlurmJobStatus) -> Table:
        table = Table(style="bold", box=box.MINIMAL)
        table.add_column("ID")
        table.add_column("Name")
        table.add_column("State")

        for task in job.tasks:
            last_column: RenderableType = task.state
            color = "grey42"
            if task.state == "RUNNING":
                color = "blue"
                last_column = Spinner("arc", task.state)
            elif task.state == "COMPLETED":
                color = "green"
                last_column = f":heavy_check_mark: {task.state}"
            elif task.state == "FAILED":
                color = "red"
                last_column = f":cross_mark: {task.state}"

            table.add_row(str(task.id), task.name, last_column, style=color)

        return table
Ejemplo n.º 5
0
def wait_cli_function(poll_func, poll_every=20):
    """
    Display a command-line spinner while calling a function repeatedly.

    Keep waiting until that function returns True

    Arguments:
       poll_func (function): Function to call
       poll_every (int): How many tenths of a second to wait between function calls. Default: 20.

    Returns:
       None. Just sits in an infite loop until the function returns True.
    """
    try:
        spinner = Spinner("dots2", "Use ctrl+c to stop waiting and force exit.")
        with Live(spinner, refresh_per_second=20) as live:
            while True:
                if poll_func():
                    break
                time.sleep(2)
    except KeyboardInterrupt:
        raise AssertionError("Cancelled!")
Ejemplo n.º 6
0
    def __init__(
        self,
        result: Result,
        *,
        verbose: bool = False,
        watching: bool = False,
        format: Literal["json", "yaml", "table"] = "json",
        fields: Optional[Type[DisplayFields]] = None,
        run_once: bool = False,
    ):
        self.result = result
        self.verbose = verbose
        self.watching = watching
        self.run_once = run_once
        self.format = format
        self.fields = fields
        self.table_style = "orange1"
        self.detail_style = "cyan"
        self.success_style = "green"
        self.fail_style = "red"
        self.spinner = Spinner("simpleDotsScrolling")

        if format == "table":
            assert fields is not None
Ejemplo n.º 7
0
# Print runtime versions
python_version = check_output(f"{PYTHON} --version", shell=True)
if python_version:
    python_version = python_version.decode("UTF-8").splitlines()[0]
    print(f"CPython: {python_version}")

pypy_version = check_output(f"{PYPY} --version", shell=True)
if pypy_version:
    tmp = pypy_version.decode("UTF-8").splitlines()[1].split()
    pypy_version = " ".join(tmp[:2])[1:]
    print(f"PyPy: {pypy_version}")

# Define styles which are used more than once
blue = Style(color="blue")
spinner = Spinner("dots", text="In progress...")

# Define table with all its columns
python_time_text = Styled("", style=blue)
pypy_time_text = Styled("", style=blue)
cwd = os.getcwd().split(os.sep)[-1]
# Show year in title - assumes folder is named aoc-YYYY
title = f":snowflake: Advent of Code {cwd.split('-')[1]} :snowflake:" if cwd.startswith("aoc-") else "Advent of Code"
table = Table(title=title, title_style=Style(color="cyan"))
table.add_column("Day")
table.add_column("Part 1")
table.add_column("Part 2", footer="[uu]Total:\n[orange3]Combined Total:[/orange3][/uu]", footer_style=blue)
table.add_column("CPython Time", min_width=16, justify="right", footer=python_time_text)
table.add_column("PyPy Time", min_width=16, justify="right", footer=pypy_time_text)

# Live update table
Ejemplo n.º 8
0
    t = Table("ID", "Port", "Protocol", "Connection Target")
    n = 0
    for _port, conn_type, ext in rem:
        t.add_row(str(n), str(_port), conn_type, ext)
        n += 1
    console.print(t)


if __name__ == "__main__":
    lineRegex = re.compile(
        r"^\s*\d+\s(TCP|UDP)\s+(?P<port>\d{1,5})->(?P<ext>\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}:\d{1,5}).+$",
        re.IGNORECASE + re.VERBOSE,
    )

    console.log("Detecting UPNP ports...")
    with Live(Spinner("aesthetic", "Getting UPnP Port Listings...", speed=0.1),
              transient=True):
        start = time.time()
        try:
            detection = run(["upnpc", "-l"], stdout=PIPE, stderr=DEVNULL)
        except KeyboardInterrupt:
            console.log("Listing cancelled.")
            sys.exit(1)
        end = time.time()

    if detection.returncode != 0:
        console.log(
            f"Got return code [red]{detection.returncode}[/] on UPnP List request. Please ensure UPnP is "
            f"enabled on your network.")
        sys.exit(detection.returncode)
Ejemplo n.º 9
0
from time import sleep

from rich.columns import Columns
from rich.panel import Panel
from rich.live import Live
from rich.text import Text
from rich.spinner import Spinner, SPINNERS

all_spinners = Columns(
    [
        Spinner(spinner_name, text=Text(repr(spinner_name), style="green"))
        for spinner_name in sorted(SPINNERS)
    ],
    column_first=True,
    expand=True,
)

with Live(
    Panel(all_spinners, title="Spinners", border_style="blue"),
    refresh_per_second=20,
) as live:
    while True:
        sleep(0.1)
Ejemplo n.º 10
0
 def __init__(self, task_name: str, task_id: str):
     self.task_name = task_name
     self.task_id = task_id
     self.renderable = Spinner("dots",
                               text=Text(f"{task_name} ({task_id})"),
                               style="green")
Ejemplo n.º 11
0
    def __enter__(self) -> 'RichUI':
        self._rich_live = Live(Spinner("bouncingBar", ""),
                               refresh_per_second=16)

        self._rich_live.start()
        return self
Ejemplo n.º 12
0
def test_spinner_create():
    Spinner("dots")
    with pytest.raises(KeyError):
        Spinner("foobar")
Ejemplo n.º 13
0
def test_spinner_markup():
    spinner = Spinner("dots", "[bold]spinning[/bold]")
    assert isinstance(spinner.text, Text)
    assert str(spinner.text) == "spinning"
Ejemplo n.º 14
0
def test_rich_measure():
    console = Console(width=80, color_system=None, force_terminal=True)
    spinner = Spinner("dots", "Foo")
    min_width, max_width = Measurement.get(console, console.options, spinner)
    assert min_width == 3
    assert max_width == 5
Ejemplo n.º 15
0
def test_spinner_create():
    spinner = Spinner("dots")
    assert spinner.time == 0.0
    with pytest.raises(KeyError):
        Spinner("foobar")
Ejemplo n.º 16
0
 def render_status(self):
     if self.status == 'processing':
         return Spinner('dots', 'processing')
     return self.status