Skip to content

Terminal Tools

Terminal tools

terminal_tools

inception

The inception module aids in creating nested terminal blocks (hence the name "inception"). It provides a Context class that manages a list of Scope instances. Each Scope instance represents a block of text that are buffered in memory and printed to the terminal at each refresh.

Scope

Source code in terminal_tools/inception.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Scope:
    def __init__(self, context: TerminalContext, text: str):
        self.context = context
        self.text = text

    def print(self):
        print(self.text)

    def refresh(self):
        """Clear the terminal and repaint with every scope up and including to this one"""
        self.context._refresh()

    def __enter__(self):
        self.context._append_scope(self)
        self.context._refresh()
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.context._remove_scope(self)
refresh()

Clear the terminal and repaint with every scope up and including to this one

Source code in terminal_tools/inception.py
41
42
43
def refresh(self):
    """Clear the terminal and repaint with every scope up and including to this one"""
    self.context._refresh()

prompts

checkbox(message, **kwargs)

Wraps inquirer's checkbox and catches KeyboardInterrupt

Source code in terminal_tools/prompts.py
118
119
120
121
122
def checkbox(message: str, **kwargs):
    """
    Wraps `inquirer`'s checkbox and catches KeyboardInterrupt
    """
    return wrap_keyboard_interrupt(lambda: inquirer_checkbox(message, **kwargs))

confirm(message, *, cancel_fallback=False, **kwargs)

Wraps inquirer's confirm input and catches KeyboardInterrupt

Source code in terminal_tools/prompts.py
125
126
127
128
129
130
131
def confirm(message: str, *, cancel_fallback: Optional[bool] = False, **kwargs):
    """
    Wraps `inquirer`'s confirm input and catches KeyboardInterrupt
    """
    return wrap_keyboard_interrupt(
        lambda: inquirer_confirm(message, **kwargs), cancel_fallback
    )

file_selector(message='select a file', *, state=None)

Lets the user select a file from the filesystem.

Parameters:

Name Type Description Default
message
str

The prompt message. Defaults to "select a file".

'select a file'
initial_path
str

Where to start the directory listing. Defaults to current working directory.

required

Returns:

Type Description
(str, optional)

The absolute path selected by the user, or None if the user cancels the prompt.

Source code in terminal_tools/prompts.py
 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
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
def file_selector(
    message: str = "select a file", *, state: Optional[FileSelectorStateManager] = None
):
    """Lets the user select a file from the filesystem.

    Args:
        message (str, optional): The prompt message. Defaults to "select a file".
        initial_path (str, optional): Where to start the directory listing.
          Defaults to current working directory.

    Returns:
        (str, optional): The absolute path selected by the user, or None if the
          user cancels the prompt.
    """
    initial_dir = state and state.get_current_path()
    if initial_dir and not os.path.isdir(initial_dir):
        initial_dir = None

    current_path = os.path.realpath(initial_dir or os.curdir)

    if os.name == "nt":
        drives = get_drives()
        drive_choices = [(drive, drive) for drive in drives]

    def is_dir(entry: str):
        return os.path.isdir(os.path.join(current_path, entry))

    while True:
        print(f"current path: {current_path}")
        choices = [
            ("[..]", ".."),
            *(
                (f"[{entry}]" if is_dir(entry) else entry, entry)
                for entry in sorted(os.listdir(current_path))
            ),
        ]

        # Add change drive option to the list of choices if on Windows
        if os.name == "nt":
            cur_drive = os.path.splitdrive(current_path)[0]
            choices.insert(
                0, (f"[Change Drive (current - {cur_drive})]", "change_drive")
            )

        selected_entry = list_input(message, choices=choices)

        if selected_entry is not None and selected_entry == "change_drive":
            selected_drive = list_input("Select a drive:", choices=drive_choices)
            if selected_drive is None:
                return None

            current_path = selected_entry = f"{selected_drive}\\"
            # clear the prompted lines
            clear_printed_lines(len(drives) + 1)

        # inquirer will show up to 14 lines including the header
        # we have one line for the current path to rewrite
        clear_printed_lines(min(len(choices), 13) + 2)

        if selected_entry is None:
            return None

        if is_dir(selected_entry):
            current_path = os.path.realpath(os.path.join(current_path, selected_entry))
        else:
            if state is not None:
                state.set_current_path(current_path)
            return os.path.join(current_path, selected_entry)

get_drives()

Returns a list of the logically assigned drives on a windows system.

Returns:

Name Type Description
list

A list of drive letters available and accessible on the system.

Source code in terminal_tools/prompts.py
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def get_drives():
    """
    Returns a list of the logically assigned drives on a windows system.

    Args:
        None

    Returns:
        list: A list of drive letters available and accessible on the system.
    """

    drives = []
    bitmask = windll.kernel32.GetLogicalDrives()

    for letter in ascii_uppercase:
        if bitmask & 1:
            drives.append(letter + ":")
        bitmask >>= 1

    return drives

int_input(message, *, min=None, max=None, default=None, **kwargs)

Wraps inquirer's text input and catches KeyboardInterrupt

Source code in terminal_tools/prompts.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
def int_input(
    message: str,
    *,
    min: Optional[int] = None,
    max: Optional[int] = None,
    default: Optional[int] = None,
    **kwargs,
) -> Optional[int]:
    """
    Wraps `inquirer`'s text input and catches KeyboardInterrupt
    """

    def validate_value(value):
        try:
            value = int(value)
        except ValueError:
            raise ValidationError("Please enter a valid integer.")

        if min is not None and value < min:
            raise ValidationError(
                f"Please enter a value greater than or equal to {min}."
            )

        if max is not None and value > max:
            raise ValidationError(f"Please enter a value less than or equal to {max}.")

        return True

    result = wrap_keyboard_interrupt(
        lambda: inquirer_text(
            message,
            validate=lambda previous_answers, value: validate_value(value),
            default=str(default) if default is not None else None,
            **kwargs,
        ),
        None,
    )
    return int(result) if result is not None else None

list_input(message, **kwargs)

Wraps inquirer's list input and catches KeyboardInterrupt

Source code in terminal_tools/prompts.py
111
112
113
114
115
def list_input(message: str, **kwargs):
    """
    Wraps `inquirer`'s list input and catches KeyboardInterrupt
    """
    return wrap_keyboard_interrupt(lambda: inquirer_list_input(message, **kwargs))

text(message, **kwargs)

Wraps inquirer's text input and catches KeyboardInterrupt

Source code in terminal_tools/prompts.py
134
135
136
137
138
def text(message: str, **kwargs):
    """
    Wraps `inquirer`'s text input and catches KeyboardInterrupt
    """
    return wrap_keyboard_interrupt(lambda: inquirer_text(message, **kwargs))

wrap_keyboard_interrupt(fn, fallback=None)

Calls fn and catches KeyboardInterrupt, returning fallback if it occurs.

Source code in terminal_tools/prompts.py
181
182
183
184
185
186
187
188
def wrap_keyboard_interrupt(fn, fallback=None):
    """
    Calls `fn` and catches KeyboardInterrupt, returning `fallback` if it occurs.
    """
    try:
        return fn()
    except KeyboardInterrupt:
        return fallback

utils

clear_printed_lines(count)

Clear the last count lines of the terminal. Useful for repainting terminal output.

Parameters:

Name Type Description Default
count
int

The number of lines to clear

required
Source code in terminal_tools/utils.py
67
68
69
70
71
72
73
74
75
76
77
78
79
def clear_printed_lines(count: int):
    """
    Clear the last `count` lines of the terminal. Useful for repainting
    terminal output.

    Args:
        count (int): The number of lines to clear
    """
    for _ in range(count + 1):
        sys.stdout.write("\033[2K")  # Clear the current line
        sys.stdout.write("\033[F")  # Move cursor up one line
    sys.stdout.write("\033[2K\r")  # Clear the last line and move to start
    sys.stdout.flush()

clear_terminal()

Clears the terminal

Source code in terminal_tools/utils.py
11
12
13
14
15
16
def clear_terminal():
    """Clears the terminal"""
    if os.name == "nt":
        os.system("cls")
    else:
        os.system("clear")

draw_box(text, *, padding_spaces=5, padding_lines=1)

Draw a box around the given text, which will be centered in the box.

Parameters:

Name Type Description Default
text
str

The text to be drawn, may be multiline. ANSI formatting and emojis are not supported, as they mess with both the character count calculation and the monospace font.

required
padding_spaces
int

Extra spaces on either side of the longest line. Defaults to 5.

5
padding_lines
int

Extra lines above and below the text. Defaults to 1.

1

Returns:

Name Type Description
str str

The text surrounded by a box.

Source code in terminal_tools/utils.py
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def draw_box(text: str, *, padding_spaces: int = 5, padding_lines: int = 1) -> str:
    """
    Draw a box around the given text, which will be centered in the box.

    Args:
        text (str): The text to be drawn, may be multiline.
          ANSI formatting and emojis are not supported, as they mess with
          both the character count calculation and the monospace font.

        padding_spaces (int, optional): Extra spaces on either side of the longest line. Defaults to 5.
        padding_lines (int, optional): Extra lines above and below the text. Defaults to 1.

    Returns:
        str: The text surrounded by a box.
    """
    lines = text.split("\n")
    width = max(len(line) for line in lines) + padding_spaces * 2

    box = ""
    box += "┌" + "─" * width + "┐\n"
    for _ in range(padding_lines):
        box += "│" + " " * width + "│\n"
    for line in lines:
        padding = " " * padding_spaces
        box += "│" + padding + line.center(width - 2 * padding_spaces) + padding + "│\n"
    for _ in range(padding_lines):
        box += "│" + " " * width + "│\n"
    box += "└" + "─" * width + "┘\n"
    return box

enable_windows_ansi_support()

Set up the Windows terminal to support ANSI escape codes, which will be needed for colored text, line clearing, and other terminal features.

Source code in terminal_tools/utils.py
52
53
54
55
56
57
58
59
60
61
62
63
64
def enable_windows_ansi_support():
    """
    Set up the Windows terminal to support ANSI escape codes, which will be needed
    for colored text, line clearing, and other terminal features.
    """
    if os.name == "nt":
        # Enable ANSI escape code support for Windows
        # On Windows, calling os.system('') with an empty string doesn't
        # run any actual command. However, there's an undocumented side
        # effect: it forces the Windows terminal to initialize or refresh
        # its state, enabling certain features like the processing of ANSI
        # escape codes, which might not otherwise be active.
        os.system("")

is_wsl()

Check if the environment is WSL2.

Source code in terminal_tools/utils.py
137
138
139
140
141
142
143
def is_wsl() -> bool:
    """Check if the environment is WSL2."""
    try:
        with open("/proc/version", "r") as f:
            return "microsoft" in f.read().lower()
    except FileNotFoundError:
        return False

print_data_frame_summary(data_frame, title, apply_color='column_data_type', caption=None)

Print a summary table for dataframes with many columns

Source code in terminal_tools/utils.py
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
def print_data_frame_summary(
    data_frame, title: str, apply_color: str = "column_data_type", caption: str = None
):
    """Print a summary table for dataframes with many columns"""
    from preprocessing.series_semantic import infer_series_semantic

    MAX_ROW_CHAR = 25

    # Create summary data
    summary_data = []
    for col in data_frame.columns:
        dtype = data_frame.select(col).dtypes[0]

        # Get example value (first non-null if possible)
        example_series = data_frame.select(col).to_series()
        example_val = None
        for val in example_series:
            if val is not None:
                example_val = str(val)
                break
        if example_val is None:
            example_val = "null"

        # Truncate long examples
        if len(example_val) > MAX_ROW_CHAR:
            example_val = example_val[:MAX_ROW_CHAR] + "..."

        # Get semantic analysis type
        try:
            semantic = infer_series_semantic(data_frame.select(col).to_series())
            analysis_type = semantic.data_type if semantic else "unknown"
        except Exception:
            analysis_type = "unknown"

        summary_data.append([col, str(dtype), example_val, analysis_type])

    # Create summary dataframe
    summary_df = pl.DataFrame(
        {
            "Column Name": [row[0] for row in summary_data],
            "Data Type": [row[1] for row in summary_data],
            "Example Value": [row[2] for row in summary_data],
            "Inferred Analyzer Input Type": [row[3] for row in summary_data],
        }
    )

    # Print with specified coloring mode
    print_data_frame(summary_df, title, apply_color, caption)

smart_print_data_frame(data_frame, title, apply_color='column_data_type', smart_print=True, caption=None)

Smart dataframe printing with adaptive display based on terminal width.

Automatically chooses between full table display and summary view based on terminal width and number of columns. Provides Rich-styled tables with configurable coloring.

Parameters:

Name Type Description Default
data_frame
DataFrame

Polars DataFrame to display

required
title
str

Title text to display above the table

required
apply_color
str | None

Color mode for the table display: - "column_data_type": Colors columns based on their Polars data types - "column-wise": Cycles through colors for each column - "row-wise": Cycles through colors for each row - None: No coloring (plain black and white display)

'column_data_type'
smart_print
bool

Controls adaptive display behavior: - True: Uses summary view for wide tables (>8 cols or narrow terminal) - False: Always uses full table display regardless of width

True
caption
str | None

Optional caption text displayed below the table

None
Display Logic
  • If smart_print=False: Always shows full table
  • If smart_print=True and (>8 columns OR estimated column width <12): Shows summary with column info, data types, and examples
  • Otherwise: Shows full table with all data

Examples:

>>> smart_print_data_frame(df, "My Data", apply_color=None)
>>> smart_print_data_frame(df, "Analysis Results", caption="Processing complete")
>>> smart_print_data_frame(df, "Wide Dataset", smart_print=False)
Source code in terminal_tools/utils.py
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
def smart_print_data_frame(
    data_frame: pl.DataFrame,
    title: str,
    apply_color: str | None = "column_data_type",
    smart_print: bool = True,
    caption: str | None = None,
) -> None:
    """Smart dataframe printing with adaptive display based on terminal width.

    Automatically chooses between full table display and summary view based on terminal
    width and number of columns. Provides Rich-styled tables with configurable coloring.

    Args:
        data_frame: Polars DataFrame to display
        title: Title text to display above the table
        apply_color: Color mode for the table display:
            - "column_data_type": Colors columns based on their Polars data types
            - "column-wise": Cycles through colors for each column
            - "row-wise": Cycles through colors for each row
            - None: No coloring (plain black and white display)
        smart_print: Controls adaptive display behavior:
            - True: Uses summary view for wide tables (>8 cols or narrow terminal)
            - False: Always uses full table display regardless of width
        caption: Optional caption text displayed below the table

    Display Logic:
        - If smart_print=False: Always shows full table
        - If smart_print=True and (>8 columns OR estimated column width <12):
          Shows summary with column info, data types, and examples
        - Otherwise: Shows full table with all data

    Examples:
        >>> smart_print_data_frame(df, "My Data", apply_color=None)
        >>> smart_print_data_frame(df, "Analysis Results", caption="Processing complete")
        >>> smart_print_data_frame(df, "Wide Dataset", smart_print=False)
    """
    if not smart_print:
        # Always use full dataframe display when smart_print is disabled
        print_data_frame(data_frame, title, apply_color, caption)
        return

    # Smart adaptive logic
    terminal_width = console.size.width
    n_cols = len(data_frame.columns)

    # Calculate if columns will be too narrow for readability
    estimated_col_width = max(60, terminal_width - 4) // max(n_cols, 1)
    min_readable_width = 12  # Minimum width for readable columns

    # Use summary if too many columns or columns would be too narrow
    if n_cols > 8 or estimated_col_width < min_readable_width:
        print_data_frame_summary(
            data_frame,
            title + " (Dataset has a large nr. of columns, showing summary instead)",
            apply_color,
            caption,
        )
    else:
        print_data_frame(data_frame, title, apply_color, caption)

wait_for_key(prompt=False)

Waits for the user to press any key

Parameters:

Name Type Description Default
prompt
bool

If true, a default text

False
Source code in terminal_tools/utils.py
19
20
21
22
23
24
25
26
27
28
def wait_for_key(prompt: bool = False):
    """Waits for the user to press any key

    Args:
        prompt (bool, optional): If true, a default text
        `Press any key to continue` will be shown. Defaults to False.
    """
    if prompt:
        print("Press any key to continue...", end="", flush=True)
    _wait_for_key()