Skip to content

Recommended way to detect interactive terminal? #1024

@hugovk

Description

@hugovk

I'm maintaining the termcolor colour library and recently added tty detection, so colour is disabled for things like pipes:

def _can_do_colour() -> bool:
    """Check env vars and for tty/dumb terminal"""
    if "ANSI_COLORS_DISABLED" in os.environ:
        return False
    if "NO_COLOR" in os.environ:
        return False
    if "FORCE_COLOR" in os.environ:
        return True
    return (
        hasattr(sys.stdout, "isatty")
        and sys.stdout.isatty()
        and os.environ.get("TERM") != "dumb"
    )

https://github.com/termcolor/termcolor/blob/ec269e608a08b33beb739b6ab5f17b9217a5692a/src/termcolor/termcolor.py#L106-L118

Unfortunately this means colour is disabled in Jupyter/JupyterLab: termcolor/termcolor#28

I see there was a plan to set isatty to True for ipykernel.iostream.OutStream, but instead it was made configurable to make sure things like pagers (less, more) didn't get confused:

So at the moment, if a Jupyter user wants colour from termcolor, they need to either set an env var FORCE_COLOR=1, or configure ipykernel.iostream.OutStream so isatty=True.

But if we wanted to add auto-detection to termcolor's _can_do_colour, what sort of thing should we query to know Jupyter is being used in an interactive way?

Thank you!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions