Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[BUG] Python 3.11 ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize #3607

Open
2 tasks done
daviddwlee84 opened this issue Jan 16, 2025 · 1 comment

Comments

@daviddwlee84
Copy link

daviddwlee84 commented Jan 16, 2025

Describe the bug

In Python 3.11 while trying to capture exception (KeyboardInterrupt during some operations) cause ValueError: Indices for islice() must be None or an integer: 0 <= x <= sys.maxsize error

Somehow we can have a chance to get instruction_index equals -1 (not always trigger and hard to reproduce in a simple script) which will crash the islice function

rich/rich/traceback.py

Lines 451 to 459 in 43d3b04

if sys.version_info >= (3, 11):
instruction_index = frame_summary.f_lasti // 2
instruction_position = next(
islice(
frame_summary.f_code.co_positions(),
instruction_index,
instruction_index + 1,
)
)

Here is how I setup Rich exception handler (with loguru)

from typing import Optional, Type
from types import TracebackType
import sys
import os
from loguru import logger
from rich.logging import RichHandler


def handle_exception(
    exc_type: Type[BaseException],
    exc_value: BaseException,
    exc_traceback: Optional[TracebackType],
    by_pass_keyboard_interrupt: bool = True,
):
    if issubclass(exc_type, KeyboardInterrupt):
        if by_pass_keyboard_interrupt:
            sys.__excepthook__(exc_type, exc_value, exc_traceback)
            logger.opt(exception=(exc_type, exc_value, exc_traceback)).warning(
                "User Keyboard Interrupt",
            )
        else:
            logger.opt(exception=(exc_type, exc_value, exc_traceback)).error(
                "User Keyboard Interrupt",
            )
    else:
        # Log all other exceptions
        logger.opt(exception=(exc_type, exc_value, exc_traceback)).error(
            "Unhandled Exception",
        )


def setup_global_logger(
    level: str = "INFO",
    rich_traceback: bool = True,
):
    logger.remove()

    logger.add(
        RichHandler(
            markup=True, rich_tracebacks=rich_traceback, tracebacks_show_locals=True
        ),
        format=(lambda _: "{message}") if rich_traceback else "{message}",
        backtrace=False,
        level=level,
    )

    sys.excepthook = handle_exception

    logger.info(f"Global loguru logger has been setup (level={level}).")

    return logger


setup_global_logger(level=os.getenv("LOG_LEVEL", "INFO"))

Platform

Click to expand

What platform (Win/Linux/Mac) are you running on? What terminal software are you using?

Linux; VSCode built-in terminal

I may ask you to copy and paste the output of the following commands. It may save some time if you do it now.

If you're using Rich in a terminal:

python -m rich.diagnose
pip freeze | grep rich
╭───────────────────────── <class 'rich.console.Console'> ─────────────────────────╮
│ A high level console interface.                                                  │
│                                                                                  │
│ ╭──────────────────────────────────────────────────────────────────────────────╮ │
│ │ <console width=206 ColorSystem.TRUECOLOR>                                    │ │
│ ╰──────────────────────────────────────────────────────────────────────────────╯ │
│                                                                                  │
│     color_system = 'truecolor'                                                   │
│         encoding = 'utf-8'                                                       │
│             file = <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'> │
│           height = 23                                                            │
│    is_alt_screen = False                                                         │
│ is_dumb_terminal = False                                                         │
│   is_interactive = True                                                          │
│       is_jupyter = False                                                         │
│      is_terminal = True                                                          │
│   legacy_windows = False                                                         │
│         no_color = False                                                         │
│          options = ConsoleOptions(                                               │
│                        size=ConsoleDimensions(width=206, height=23),             │
│                        legacy_windows=False,                                     │
│                        min_width=1,                                              │
│                        max_width=206,                                            │
│                        is_terminal=True,                                         │
│                        encoding='utf-8',                                         │
│                        max_height=23,                                            │
│                        justify=None,                                             │
│                        overflow=None,                                            │
│                        no_wrap=False,                                            │
│                        highlight=None,                                           │
│                        markup=None,                                              │
│                        height=None                                               │
│                    )                                                             │
│            quiet = False                                                         │
│           record = False                                                         │
│         safe_box = True                                                          │
│             size = ConsoleDimensions(width=206, height=23)                       │
│        soft_wrap = False                                                         │
│           stderr = False                                                         │
│            style = None                                                          │
│         tab_size = 8                                                             │
│            width = 206                                                           │
╰──────────────────────────────────────────────────────────────────────────────────╯
╭─── <class 'rich._windows.WindowsConsoleFeatures'> ────╮
│ Windows features available.                           │
│                                                       │
│ ╭───────────────────────────────────────────────────╮ │
│ │ WindowsConsoleFeatures(vt=False, truecolor=False) │ │
│ ╰───────────────────────────────────────────────────╯ │
│                                                       │
│ truecolor = False                                     │
│        vt = False                                     │
╰───────────────────────────────────────────────────────╯
╭────── Environment Variables ───────╮
│ {                                  │
│     'TERM': 'xterm-256color',      │
│     'COLORTERM': 'truecolor',      │
│     'CLICOLOR': None,              │
│     'NO_COLOR': None,              │
│     'TERM_PROGRAM': 'vscode',      │
│     'COLUMNS': None,               │
│     'LINES': None,                 │
│     'JUPYTER_COLUMNS': None,       │
│     'JUPYTER_LINES': None,         │
│     'JPY_PARENT_PID': None,        │
│     'VSCODE_VERBOSE_LOGGING': None │
│ }                                  │
╰────────────────────────────────────╯
platform="Linux"
rich==13.9.4
Copy link

Thank you for your issue. Give us a little time to review it.

PS. You might want to check the FAQ if you haven't done so already.

This is an automated reply, generated by FAQtory

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant