Skip to content

Utilities

Shell

In order to provide a nice interface for the user here are some useful functions.

clear_shell()

Clears any previous text in the shell

Source code in src/utils/shell.py
 7
 8
 9
10
11
12
def clear_shell() -> None:
    """Clears any previous text in the shell"""
    if platform in ["linux", "linux2", "darwin"]:
        os.system("clear")
    elif platform == "win32":
        os.system("cls")

get_int(options, start=1)

Gets an integer from the user

Parameters:

Name Type Description Default
options list[str]

The list of options to choose from

required
start int, optional

The starting index of the options. This feature is useful if you also use the print_options function. By default 1.

1

Returns:

Type Description
int | None

Returns the integer if it is in the list of options, otherwise returns None

Raises:

Type Description
ValueError

If the input was invalid, but the error is caught within the function

Source code in src/utils/shell.py
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def get_int(options: list[str], start: int = 1) -> int | None:
    """Gets an integer from the user

    Parameters
    ----------
    options : list[str]
        The list of options to choose from
    start : int, optional
        The starting index of the options. This feature is useful if you also use
        the `print_options` function. _By default `1`._

    Returns
    -------
    int | None
        Returns the integer if it is in the list of options, otherwise returns None

    Raises
    ------
    ValueError
        If the input was invalid, but the error is caught within the function
    """
    print()

    if len(options) == 0:
        logger.warning("The options list is empty")
        return None

    choice = None
    while choice is None:
        try:
            choice = int(input("Enter a number: "))
            if choice < start or choice > len(options) + start - 1:
                raise ValueError
        except (ValueError, TypeError):
            logger.warning("Invalid input")
            choice = None

    return choice  # type: ignore

print_options(options)

Prints a list of options to the shell

Parameters:

Name Type Description Default
options list[str]

The list of options to print

required
Source code in src/utils/shell.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
def print_options(options: list[str]) -> None:
    """Prints a list of options to the shell

    Parameters
    ----------
    options : list[str]
        The list of options to print
    """
    print()

    if len(options) == 0:
        logger.warning("The options list is empty")
        return None

    for index, option in enumerate(options, start=1):
        print(f"{index}: {option}")

    return None