Git Product home page Git Product logo

termcolor's Introduction

termcolor

PyPI version Supported Python versions PyPI downloads GitHub Actions status Codecov Licence Code style: Black Tidelift

Installation

From PyPI

python3 -m pip install --upgrade termcolor

From source

git clone https://github.com/termcolor/termcolor
cd termcolor
python3 -m pip install .

Demo

To see demo output, run:

python3 -m termcolor

Example

import sys

from termcolor import colored, cprint

text = colored("Hello, World!", "red", attrs=["reverse", "blink"])
print(text)
cprint("Hello, World!", "green", "on_red")

print_red_on_cyan = lambda x: cprint(x, "red", "on_cyan")
print_red_on_cyan("Hello, World!")
print_red_on_cyan("Hello, Universe!")

for i in range(10):
    cprint(i, "magenta", end=" ")

cprint("Attention!", "red", attrs=["bold"], file=sys.stderr)

Text properties

Text colors Text highlights Attributes
black on_black bold
red on_red dark
green on_green underline
yellow on_yellow blink
blue on_blue reverse
magenta on_magenta concealed
cyan on_cyan strike
white on_white
light_grey on_light_grey
dark_grey on_dark_grey
light_red on_light_red
light_green on_light_green
light_yellow on_light_yellow
light_blue on_light_blue
light_magenta on_light_magenta
light_cyan on_light_cyan

Terminal properties

Terminal bold dark underline blink reverse concealed
xterm yes no yes bold yes yes
linux yes yes bold yes yes no
rxvt yes no yes bold/black yes no
dtterm yes yes yes reverse yes yes
teraterm reverse no yes rev/red yes no
aixterm normal no yes no yes yes
PuTTY color no yes no yes no
Windows no no no no yes no
Cygwin SSH yes no color color color yes
Mac Terminal yes no yes yes yes yes

Overrides

Terminal colour detection can be disabled or enabled in several ways.

In order of precedence:

  1. Calling colored or cprint with a truthy no_color disables colour.
  2. Calling colored or cprint with a truthy force_color forces colour.
  3. Setting the ANSI_COLORS_DISABLED environment variable to any value disables colour.
  4. Setting the NO_COLOR environment variable to any value disables colour.
  5. Setting the FORCE_COLOR environment variable to any value forces colour.
  6. Setting the TERM environment variable to dumb, or using such a dumb terminal, disables colour.
  7. Finally, termcolor will attempt to detect whether the terminal supports colour.

termcolor's People

Contributors

cozydoomer avatar felixonmars avatar hugovk avatar jdufresne avatar marcin-serwin avatar muzhig avatar pre-commit-ci[bot] avatar renovate[bot] avatar tmetzl avatar xiaolichan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

termcolor's Issues

Apache/mod_wsgi log object is not associated with a file descriptor.

Apache/mod_wsgi log object is not associated with a file descriptor.
When upgrading from 2.3.0 to 2.4.0 in my Django project
Error probably due to change in isatty

    # Then check system:
    if os.environ.get("TERM") == "dumb":
        return False
    if not hasattr(sys.stdout, "fileno"):
        return False
    try:
        return os.isatty(sys.stdout.fileno()) …
    except io.UnsupportedOperation:
        return sys.stdout.isatty()

Export types from library for type checking

I am writing a logger with termcolor, and want to use Attribute, Color & Highlight from termcolor._types.
I am using mypy with aggressive type-checking so it will not type check unless I import the types (or ignore the error).

class ColorFormatter:
    FORMATS: ClassVar[dict[int, tuple[Color, list[Attribute] | None]]] = {
        logging.DEBUG: ("grey", None),
        logging.INFO: ("white", None),
        logging.WARNING: ("yellow", ["bold"]),
        logging.ERROR: ("red", ["bold"]),
        logging.CRITICAL: ("magenta", ["underline", "bold"]),
    }

Is it possible to export the types from __init__.py?

feature request: force colours

Hi,

I have a special case where I pipe my script using termcolor to fzf --ansi to keep colours. But it seems that _can_do_colour() wants stdout to be interactive, so this is not possible for now.

Would it be possible to init the module with forced colours?

The isatty check is always done on stdout, even if the output file is different

It seems that termcolor always checks sys.stdout for being a TTY, instead of the file you are actually outputting to.
A consequence of this is that termcolor will not color output to sys.stderr when a program is used in a pipe. This is an unfortunate limitation.

It makes sense that colored always checks sys.stdout, since it has no way of knowing what the output file will be. However, I would like to request there to be some way of explicitly specifying the intended output file, perhaps via an optional output_file argument.

For cprint, this is arguably a bug. I believe it could be fixed by looking for the file argument in kwargs and then checking that instead of sys.stdout.

Document `NO_COLOR` and `FORCE_COLOR` overrides

Document in the README the parameters, env vars and terminal detection checked here for overriding/using colours:

def _can_do_colour(
*, no_color: bool | None = None, force_color: bool | None = None
) -> bool:
"""Check env vars and for tty/dumb terminal"""
# First check overrides:
# "User-level configuration files and per-instance command-line arguments should
# override $NO_COLOR. A user should be able to export $NO_COLOR in their shell
# configuration file as a default, but configure a specific program in its
# configuration file to specifically enable color."
# https://no-color.org
if no_color is not None and no_color:
return False
if force_color is not None and force_color:
return True
# Then check env vars:
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
# Then check system:
if os.environ.get("TERM") == "dumb":
return False
if not hasattr(sys.stdout, "fileno"):
return False
try:
return os.isatty(sys.stdout.fileno())
except io.UnsupportedOperation:
return sys.stdout.isatty()

(Re: #33 (comment))

No demo output

Here's the problem (on Arch Linux):

$ sudo pacman -S python-termcolor
resolving dependencies...
looking for conflicting packages...

Packages (1) python-termcolor-2.1.0-1

Total Installed Size:  0.02 MiB

:: Proceed with installation? [Y/n] 
(1/1) checking keys in keyring                                               [###########################################] 100%
(1/1) checking package integrity                                             [###########################################] 100%
(1/1) loading package files                                                  [###########################################] 100%
(1/1) checking for file conflicts                                            [###########################################] 100%
(1/1) checking available disk space                                          [###########################################] 100%
:: Processing package changes...
(1/1) installing python-termcolor                                            [###########################################] 100%
:: Running post-transaction hooks...
(1/1) Arming ConditionNeedsUpdate...

$ python3 -m termcolor
/usr/bin/python3: No module named termcolor.__main__; 'termcolor' is a package and cannot be directly executed

Light/Dark colors dont work

I see error when I try to use the recently added colors (light/dark , black)

Traceback (most recent call last):
  File "/Users/noob/Documents/code-sandbox/py/python-experiments/termcolor-test.py", line 60, in <module>
    cprint(f"Color: {c}", c, attrs=["bold"])
  File "/Users/noob/.pyenv/versions/3.9.14/lib/python3.9/site-packages/termcolor/termcolor.py", line 171, in cprint
    print((colored(text, color, on_color, attrs)), **kwargs)
  File "/Users/noob/.pyenv/versions/3.9.14/lib/python3.9/site-packages/termcolor/termcolor.py", line 147, in colored
    text = fmt_str % (COLORS[color], text)
KeyError: 'black'

Even when running the demo I only see the limited colors (as opposed to screenshot in PR #32)
Screenshot 2023-01-03 at 17 38 20

My version is 2.1.1

╰─ pip show termcolor                                                                                                                                                                                                                                                                                                     
Name: termcolor
Version: 2.1.1
Summary: ANSI color formatting for output in terminal
Home-page: 
Author: 
Author-email: Konstantin Lepa <[email protected]>
License: MIT

Tried on both MacOS Terminal and Alacritty with zsh.

Is there something I'm missing here?
How could I use the new color shades?

python3.6 install tensorflow1.12.0 rely on termcolor, install termcolor failed!

Collecting termcolor>=1.1.0
  Downloading http://pypi.doubanio.com/packages/8a/48/a76be51647d0eb9f10e2a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz (3.9 kB)
  Preparing metadata (setup.py) ... error
  ERROR: Command errored out with exit status -11:
   command: /Users/zhangchengshu/.pyenv/versions/3.6.6/bin/python3.6 -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/tq/cftlwh814sd6d4vwgqr4g83w0000gn/T/pip-install-_p8l8tck/termcolor_903fd6b64ae740379c6b8b8ca332bcd8/setup.py'"'"'; __file__='"'"'/private/var/folders/tq/cftlwh814sd6d4vwgqr4g83w0000gn/T/pip-install-_p8l8tck/termcolor_903fd6b64ae740379c6b8b8ca332bcd8/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/tq/cftlwh814sd6d4vwgqr4g83w0000gn/T/pip-pip-egg-info-yhblk4ou
       cwd: /private/var/folders/tq/cftlwh814sd6d4vwgqr4g83w0000gn/T/pip-install-_p8l8tck/termcolor_903fd6b64ae740379c6b8b8ca332bcd8/
  Complete output (0 lines):
  ----------------------------------------
WARNING: Discarding http://pypi.doubanio.com/packages/8a/48/a76be51647d0eb9f10e2a4511bf3ffb8cc1e6b14e9e4fab46173aa79f981/termcolor-1.1.0.tar.gz#sha256=1d6d69ce66211143803fbc56652b41d73b4a400a2891d7bf7a1cdf4c02de613b (from http://pypi.doubanio.com/simple/termcolor/). Command errored out with exit status -11: python setup.py egg_info Check the logs for full command output.
ERROR: Could not find a version that satisfies the requirement termcolor>=1.1.0 (from tensorflow) (from versions: 0.1, 0.1.1, 0.1.2, 0.2, 1.0.0, 1.0.1, 1.1.0)
ERROR: No matching distribution found for termcolor>=1.1.0

python version 3.6.6
pip 21.3.1
setuptools 57.0.0

Black text color

Could you explain how to make text black, i see no constant for it?

At the moment i do so on_blue = lambda text: colored(colorama.Fore.BLACK+text, on_color='on_blue', attrs=['bold'])

No longer works in PyCharm console

In reference to #28

The issue: termcolor no longer colorizes text in PyCharm.
The issue affects Python Console:

Screenshot 2022-11-21 103250

Screenshot 2022-11-21 103447

It also affects the console that PyCharm outputs to when you use the Run button:

Screenshot 2022-11-21 102823

Screenshot 2022-11-21 102955

  • Version 2.0.1 works fine
  • Versions 2.1.0 and 2.1.1 don't work on their own and require a workaround os.environ["FORCE_COLOR"] = "1"

Terminal check not cached

Every time a colored message is printed, the module checks again in colored output is enabled. This is unnecessarily slow. The result of the check should better be cached.

The "light_" colors don't work.

The "light_" values don't work, but the regular values do. Don't worry that it's printing control characters for green, it works fine on the terminal. But the use of "light_magenta" fails as shown:

Python 3.6.10 |Anaconda, Inc.| (default, Mar 25 2020, 23:51:54)
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from termcolor import colored
>>> colored('Works','green')
'\x1b[32mWorks\x1b[0m'
>>> colored('Fails','light_magenta')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/app/anaconda_3.6/lib/python3.6/site-packages/termcolor.py", line 105, in colored
    text = fmt_str % (COLORS[color], text)
KeyError: 'light_magenta'

It's odd because you code clearly shows light_magenta all over the place. I have the same success with other base colors ('white', etc.), and have the same trouble with other light_* colors.

My $TERM is set to "xterm".

Thoughts?

Kali Linux "sh: 1: color: Permission denied"

The termcolor module works on Windows but when I try to run it on Kali Linux, it says "sh: 1: color: Permission denied" on my terminal. However, my program still works. Do you know what the cause of the message is? Thank you!

isatty check is too simple

I noticed that coloured output stopped working a few months back. Took a bit of poking around. Wondered if the library might be checking isatty(). Found the code change. Also verified my use case by setting FORCE_COLOR=1.

What I had been doing for long output, mytool | less -R.

You will notice, from the perspective of mytool, isatty() gives different answers for stdin and stdout.

But, it's not that simple. Different tools and different code have diffrent needs. Sometimes it's best that the library do the result because it doesn't know the context.

Code archeology notes

Notes on reconstructing history

Because there's no record of this project's code repo, I thought it would be nevertheless be good to have some sort of history.

I downloaded the old sdists from https://pypi.org/project/termcolor/#history to reconstruct it.

This repo had started from an initial commit of the latest 1.1.0 sdist.

I followed https://stackoverflow.com/a/59548348/724176 to add new commits before the current repo's initial commit.

For each commit, I took the sdist contents, and made a single commit:

Version X.Y.Z

Co-authored-by: Konstantin Lepa <[email protected]>

and committed like gc --date="2011-01-13T18:45:33.979856Z", using the upload_time_iso_8601 of the release from https://pypi.org/pypi/termcolor/json


Because this rewrote the Git history of this repo, if you have a clone, I suggest deleting and re-cloning. I'm doing this now to get a clean starting point to continue and won't be rewriting history once this is sorted :)


First pass, I had this locally:

image

But this on GitHub:

image

Seems there's also a difference between "author date" and "commit date":

https://github.com/orgs/community/discussions/22695#discussioncomment-3237743

So I re-filtered with their suggestion:

git filter-branch --env-filter 'export GIT_COMMITTER_DATE="$GIT_AUTHOR_DATE"'
git push -f

And it now looks good locally:

image

And on GitHub:

image

...

image
image

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

Awaiting Schedule

These updates are awaiting their schedule. Click on a checkbox to get an update now.

  • Update codecov/codecov-action action to v4.3.0

Detected dependencies

github-actions
.github/workflows/deploy.yml
  • actions/checkout v4
  • hynek/build-and-inspect-python-package v2
  • actions/download-artifact v4
  • actions/download-artifact v4
.github/workflows/labels.yml
  • actions/checkout v4
  • micnncim/action-label-syncer v1
.github/workflows/lint.yml
  • actions/checkout v4
  • actions/setup-python v5
  • pre-commit/action v3.0.1
.github/workflows/release-drafter.yml
  • release-drafter/release-drafter v6
.github/workflows/require-pr-label.yml
  • mheap/github-action-required-labels v5
.github/workflows/test.yml
  • actions/checkout v4
  • actions/setup-python v5
  • codecov/codecov-action v4.2.0
pep621
pyproject.toml

  • Check this box to trigger a request for Renovate to run again on this repository

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.