Simple cross-platform colored terminal text in Python

Related tags

colorama
Overview
Latest Version Supported Python versions Build Status

Colorama

Makes ANSI escape character sequences (for producing colored terminal text and cursor positioning) work under MS Windows.

PyPI for releases | Github for source | Colorama for enterprise on Tidelift

If you find Colorama useful, please Donate with Paypal to the authors. Thank you!

Installation

Tested on CPython 2.7, 3.5, 3.6, 3.7, 3.8 and 3.9 and Pypy 2.7.

No requirements other than the standard library.

pip install colorama
# or
conda install -c anaconda colorama

Description

ANSI escape character sequences have long been used to produce colored terminal text and cursor positioning on Unix and Macs. Colorama makes this work on Windows, too, by wrapping stdout, stripping ANSI sequences it finds (which would appear as gobbledygook in the output), and converting them into the appropriate win32 calls to modify the state of the terminal. On other platforms, Colorama does nothing.

This has the upshot of providing a simple cross-platform API for printing colored terminal text from Python, and has the happy side-effect that existing applications or libraries which use ANSI sequences to produce colored output on Linux or Macs can now also work on Windows, simply by calling colorama.init().

An alternative approach is to install ansi.sys on Windows machines, which provides the same behaviour for all applications running in terminals. Colorama is intended for situations where that isn't easy (e.g., maybe your app doesn't have an installer.)

Demo scripts in the source code repository print some colored text using ANSI sequences. Compare their output under Gnome-terminal's built in ANSI handling, versus on Windows Command-Prompt using Colorama:

ANSI sequences on Ubuntu under gnome-terminal.

Same ANSI sequences on Windows, using Colorama.

These screenshots show that, on Windows, Colorama does not support ANSI 'dim text'; it looks the same as 'normal text'.

Usage

Initialisation

Applications should initialise Colorama using:

from colorama import init
init()

On Windows, calling init() will filter ANSI escape sequences out of any text sent to stdout or stderr, and replace them with equivalent Win32 calls.

On other platforms, calling init() has no effect (unless you request other optional functionality; see "Init Keyword Args", below). By design, this permits applications to call init() unconditionally on all platforms, after which ANSI output should just work.

To stop using Colorama before your program exits, simply call deinit(). This will restore stdout and stderr to their original values, so that Colorama is disabled. To resume using Colorama again, call reinit(); it is cheaper than calling init() again (but does the same thing).

Colored Output

Cross-platform printing of colored text can then be done using Colorama's constant shorthand for ANSI escape sequences:

from colorama import Fore, Back, Style
print(Fore.RED + 'some red text')
print(Back.GREEN + 'and with a green background')
print(Style.DIM + 'and in dim text')
print(Style.RESET_ALL)
print('back to normal now')

...or simply by manually printing ANSI sequences from your own code:

print('\033[31m' + 'some red text')
print('\033[39m') # and reset to default color

...or, Colorama can be used in conjunction with existing ANSI libraries such as the venerable Termcolor or the fabulous Blessings. This is highly recommended for anything more than trivial coloring:

from colorama import init
from termcolor import colored

# use Colorama to make Termcolor work on Windows too
init()

# then use Termcolor for all colored text output
print(colored('Hello, World!', 'green', 'on_red'))

Available formatting constants are:

Fore: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Back: BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE, RESET.
Style: DIM, NORMAL, BRIGHT, RESET_ALL

Style.RESET_ALL resets foreground, background, and brightness. Colorama will perform this reset automatically on program exit.

Cursor Positioning

ANSI codes to reposition the cursor are supported. See demos/demo06.py for an example of how to generate them.

Init Keyword Args

init() accepts some **kwargs to override default behaviour.

init(autoreset=False):

If you find yourself repeatedly sending reset sequences to turn off color changes at the end of every print, then init(autoreset=True) will automate that:

from colorama import init
init(autoreset=True)
print(Fore.RED + 'some red text')
print('automatically back to default color again')
init(strip=None):
Pass True or False to override whether ANSI codes should be stripped from the output. The default behaviour is to strip if on Windows or if output is redirected (not a tty).
init(convert=None):
Pass True or False to override whether to convert ANSI codes in the output into win32 calls. The default behaviour is to convert if on Windows and output is to a tty (terminal).
init(wrap=True):

On Windows, Colorama works by replacing sys.stdout and sys.stderr with proxy objects, which override the .write() method to do their work. If this wrapping causes you problems, then this can be disabled by passing init(wrap=False). The default behaviour is to wrap if autoreset or strip or convert are True.

When wrapping is disabled, colored printing on non-Windows platforms will continue to work as normal. To do cross-platform colored output, you can use Colorama's AnsiToWin32 proxy directly:

import sys
from colorama import init, AnsiToWin32
init(wrap=False)
stream = AnsiToWin32(sys.stderr).stream

# Python 2
print >>stream, Fore.BLUE + 'blue text on stderr'

# Python 3
print(Fore.BLUE + 'blue text on stderr', file=stream)

Recognised ANSI Sequences

ANSI sequences generally take the form:

ESC [ <param> ; <param> ... <command>

Where <param> is an integer, and <command> is a single letter. Zero or more params are passed to a <command>. If no params are passed, it is generally synonymous with passing a single zero. No spaces exist in the sequence; they have been inserted here simply to read more easily.

The only ANSI sequences that Colorama converts into win32 calls are:

ESC [ 0 m       # reset all (colors and brightness)
ESC [ 1 m       # bright
ESC [ 2 m       # dim (looks same as normal brightness)
ESC [ 22 m      # normal brightness

# FOREGROUND:
ESC [ 30 m      # black
ESC [ 31 m      # red
ESC [ 32 m      # green
ESC [ 33 m      # yellow
ESC [ 34 m      # blue
ESC [ 35 m      # magenta
ESC [ 36 m      # cyan
ESC [ 37 m      # white
ESC [ 39 m      # reset

# BACKGROUND
ESC [ 40 m      # black
ESC [ 41 m      # red
ESC [ 42 m      # green
ESC [ 43 m      # yellow
ESC [ 44 m      # blue
ESC [ 45 m      # magenta
ESC [ 46 m      # cyan
ESC [ 47 m      # white
ESC [ 49 m      # reset

# cursor positioning
ESC [ y;x H     # position cursor at x across, y down
ESC [ y;x f     # position cursor at x across, y down
ESC [ n A       # move cursor n lines up
ESC [ n B       # move cursor n lines down
ESC [ n C       # move cursor n characters forward
ESC [ n D       # move cursor n characters backward

# clear the screen
ESC [ mode J    # clear the screen

# clear the line
ESC [ mode K    # clear the line

Multiple numeric params to the 'm' command can be combined into a single sequence:

ESC [ 36 ; 45 ; 1 m     # bright cyan text on magenta background

All other ANSI sequences of the form ESC [ <param> ; <param> ... <command> are silently stripped from the output on Windows.

Any other form of ANSI sequence, such as single-character codes or alternative initial characters, are not recognised or stripped. It would be cool to add them though. Let me know if it would be useful for you, via the Issues on GitHub.

Status & Known Problems

I've personally only tested it on Windows XP (CMD, Console2), Ubuntu (gnome-terminal, xterm), and OS X.

Some presumably valid ANSI sequences aren't recognised (see details below), but to my knowledge nobody has yet complained about this. Puzzling.

See outstanding issues and wish-list: https://github.com/tartley/colorama/issues

If anything doesn't work for you, or doesn't do what you expected or hoped for, I'd love to hear about it on that issues list, would be delighted by patches, and would be happy to grant commit access to anyone who submits a working patch or two.

If you're hacking on the code, see README-hacking.md.

License

Copyright Jonathan Hartley & Arnon Yaari, 2013-2020. BSD 3-Clause license; see LICENSE file.

Professional support

Tidelift Professional support for colorama is available as part of the Tidelift Subscription. Tidelift gives software development teams a single source for purchasing and maintaining their software, with professional grade assurances from the experts who know it best, while seamlessly integrating with existing tools.

Thanks

  • Marc Schlaich (schlamar) for a setup.py fix for Python2.5.
  • Marc Abramowitz, reported & fixed a crash on exit with closed stdout, providing a solution to issue #7's setuptools/distutils debate, and other fixes.
  • User 'eryksun', for guidance on correctly instantiating ctypes.windll.
  • Matthew McCormick for politely pointing out a longstanding crash on non-Win.
  • Ben Hoyt, for a magnificent fix under 64-bit Windows.
  • Jesse at Empty Square for submitting a fix for examples in the README.
  • User 'jamessp', an observant documentation fix for cursor positioning.
  • User 'vaal1239', Dave Mckee & Lackner Kristof for a tiny but much-needed Win7 fix.
  • Julien Stuyck, for wisely suggesting Python3 compatible updates to README.
  • Daniel Griffith for multiple fabulous patches.
  • Oscar Lesta for a valuable fix to stop ANSI chars being sent to non-tty output.
  • Roger Binns, for many suggestions, valuable feedback, & bug reports.
  • Tim Golden for thought and much appreciated feedback on the initial idea.
  • User 'Zearin' for updates to the README file.
  • John Szakmeister for adding support for light colors
  • Charles Merriam for adding documentation to demos
  • Jurko for a fix on 64-bit Windows CPython2.5 w/o ctypes
  • Florian Bruhin for a fix when stdout or stderr are None
  • Thomas Weininger for fixing ValueError on Windows
  • Remi Rampin for better Github integration and fixes to the README file
  • Simeon Visser for closing a file handle using 'with' and updating classifiers to include Python 3.3 and 3.4
  • Andy Neff for fixing RESET of LIGHT_EX colors.
  • Jonathan Hartley for the initial idea and implementation.
Issues
  • impossible to install colorama

    impossible to install colorama

    since few minutes, it seems to be impossible to install colorama:

    pip3 install --upgrade colorama
    Collecting colorama
      Using cached https://files.pythonhosted.org/packages/cb/fe/bfc4d807aa43a183ab387340f524a0bb086624f2c5935bd08e647b54b269/colorama-0.4.2.tar.gz
        Complete output from command python setup.py egg_info:
        Traceback (most recent call last):
          File "<string>", line 1, in <module>
          File "/tmp/pip-build-s_73iow0/colorama/setup.py", line 36, in <module>
            long_description=read_file('README.rst'),
          File "/tmp/pip-build-s_73iow0/colorama/setup.py", line 18, in read_file
            with open(os.path.join(os.path.dirname(__file__), path)) as fp:
        FileNotFoundError: [Errno 2] No such file or directory: '/tmp/pip-build-s_73iow0/colorama/README.rst'
    
        ----------------------------------------
    Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-s_73iow0/colorama/
    
    opened by ericLemanissier 28
  • Escape sequences are unprocessed on Windows with TERM set

    Escape sequences are unprocessed on Windows with TERM set

    On Windows, when the environment variable TERM is set to any value, escape sequences will be printed unprocessed (no colored output). Concerning the values of TERM/the terminals where this happens, I'm still waiting for user feedback (see msiemens/PyGitUp#24).

    According to git bisect this behaviour has been introduced in 961428e6c1c3a6855da5dedccfc418f295b54c25.

    bug 
    opened by msiemens 17
  • Colorama master doesn't work with The Fuck; 0.3.3 partly works; 0.3.2 works

    Colorama master doesn't work with The Fuck; 0.3.3 partly works; 0.3.2 works

    Windows 7, Python 2.7, Git BASH.

    • The Fuck works properly with Colorama 0.3.2.
    • The Fuck works with Colorama 0.3.3 but the text isn't coloured and it prints characters like ←[1m.
    • The Fuck doesn't work with Colorama master branch and the text isn't coloured and it prints characters like ←[1m.

    Install latest dev version:

    ~/github/colorama (master)
    $ python setup.py develop
    running develop
    running egg_info
    writing colorama.egg-info\PKG-INFO
    writing top-level names to colorama.egg-info\top_level.txt
    writing dependency_links to colorama.egg-info\dependency_links.txt
    reading manifest file 'colorama.egg-info\SOURCES.txt'
    reading manifest template 'MANIFEST.in'
    writing manifest file 'colorama.egg-info\SOURCES.txt'
    running build_ext
    Creating c:\python27\lib\site-packages\colorama.egg-link (link to .)
    Adding colorama 0.3.3 to easy-install.pth file
    
    Installed c:\users\hugovk\github\colorama
    Processing dependencies for colorama==0.3.3
    Finished processing dependencies for colorama==0.3.3
    

    Create a new branch, try and push it, then use The Fuck to push it properly:

    ~/github/colorama (master)
    $ git checkout -b test_branch1
    Switched to a new branch 'test_branch1'
    
    ~/github/colorama (test_branch1)
    $ git push
    fatal: The current branch test_branch1 has no upstream branch.
    To push the current branch and set the remote as upstream, use
    
        git push --set-upstream origin test_branch1
    
    
    ~/github/colorama (test_branch1)
    $ fuck
    ←[1mgit push --set-upstream origin test_branch1←[0m
    fatal: remote part of refspec is not a valid name in
    Unexpected end of command stream
    

    Text was monochrome, command didn't work.


    Try the same thing with Colorama 0.3.2:

    ~/github/colorama (test_branch1)
    $ pip install colorama==0.3.2
    Collecting colorama==0.3.2
      Using cached colorama-0.3.2.tar.gz
    Installing collected packages: colorama
      Found existing installation: colorama 0.3.3
        Uninstalling colorama-0.3.3:
          Successfully uninstalled colorama-0.3.3
      Running setup.py install for colorama
    Successfully installed colorama-0.3.3
    
    ~/github/colorama (test_branch1)
    $ git push
    fatal: The current branch test_branch1 has no upstream branch.
    To push the current branch and set the remote as upstream, use
    
        git push --set-upstream origin test_branch1
    
    
    ~/github/colorama (test_branch1)
    $ fuck
    git push --set-upstream origin test_branch1
    Total 0 (delta 0), reused 0 (delta 0)
    To https://github.com/hugovk/colorama
     * [new branch]      test_branch1 -> test_branch1
    Branch test_branch1 set up to track remote branch test_branch1 from origin.
    

    The command worked, and those last five lines were coloured light grey.


    And with Colorama 0.3.3:

    ~/github/colorama (test_branch1)
    $ pip install colorama==0.3.3
    Collecting colorama==0.3.3
      Using cached colorama-0.3.3.tar.gz
    Installing collected packages: colorama
      Found existing installation: colorama 0.3.2
        Uninstalling colorama-0.3.2:
          Successfully uninstalled colorama-0.3.2
      Running setup.py install for colorama
    Successfully installed colorama-0.3.3
    
    ~/github/colorama (test_branch1)
    $ git checkout -b test_branch2
    Switched to a new branch 'test_branch2'
    
    ~/github/colorama (test_branch2)
    $ git push
    fatal: The current branch test_branch2 has no upstream branch.
    To push the current branch and set the remote as upstream, use
    
        git push --set-upstream origin test_branch2
    
    
    ~/github/colorama (test_branch2)
    $ fuck
    ←[1mgit push --set-upstream origin test_branch2←[0m
    Total 0 (delta 0), reused 0 (delta 0)
    To https://github.com/hugovk/colorama
     * [new branch]      test_branch2 -> test_branch2
    Branch test_branch2 set up to track remote branch test_branch2 from origin.
    

    The command worked, but the text is monochrome and shows ←[1m type characters.


    Note the above was with thefuck==1.45, but similar results are had with latest thefuck==3.1.

    bug 
    opened by hugovk 13
  • input() with color will crash line

    input() with color will crash line

    I want to color the prompt text using following code: input(Fore.GREEN+'some prompt'+Style.RESET_ALL) but this will crash the line like this: 2020-10-25-120731_971x51_scrot

    The "aaaaaaaaaa....." strings don't reach the end of the line and override start of this line.

    I can't figure out this issue, can anyone help?

    opened by u23a 11
  • Use wheels.

    Use wheels.

    I noticed that there is no wheels package on the pypi page even if there is a setup.cfg. Just python setup.py bdist_wheel and then uploading would do.

    feature-request 
    opened by SanketDG 11
  • unicode variables printed out

    unicode variables printed out

    Hello! Some of my users report seeing u'\x1b[96m prepending text instead of line with coloured output. I can't reproduce this bug on my machine but it since has been confirmed by others. No visible connection to OS/terminal/shell of something like that.

    I asked all of them to run following snippet

    import colorama
    from colorama import Fore
    print(Fore.BLUE + “Hello World”)
    

    ... and weirdly, in such case output is coloured as expected, no unicode symbols.

    Could you please advice what may be the problem?

    Thanks!

    opened by ror6ax 11
  • several fixes to erase_data

    several fixes to erase_data

    Fixes multiple problems with \033[nJ, also fixes issues #46 and #55 from Google Code.

    opened by wiggin15 10
  • Issue on windows 10 Python 3.6

    Issue on windows 10 Python 3.6

    Running pytest 3.0.5 and colorama 0.3.7 on Python 3.6 on a windows 10 machine I got the following error. I think that Python 3.6 made some change to console handling on windows so it may be related.

    Microsoft Windows [version 10.0.14393]
    
    Traceback (most recent call last):
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\main.py", line 98, in wrap_session
        session.exitstatus = doit(config, session) or 0
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\main.py", line 133, in _main
        config.hook.pytest_runtestloop(session=session)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 745, in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 339, in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 334, in <lambda>
        _MultiCall(methods, kwargs, hook.spec_opts).execute()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 614, in execute
        res = hook_impl.function(*args)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\main.py", line 154, in pytest_runtestloop
        item.config.hook.pytest_runtest_protocol(item=item, nextitem=nextitem)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 745, in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 339, in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 334, in <lambda>
        _MultiCall(methods, kwargs, hook.spec_opts).execute()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 613, in execute
        return _wrapped_call(hook_impl.function(*args), self.execute)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 254, in _wrapped_call
        return call_outcome.get_result()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 279, in get_result
        raise ex[1].with_traceback(ex[2])
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 265, in __init__
        self.result = func()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 614, in execute
        res = hook_impl.function(*args)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\runner.py", line 66, in pytest_runtest_protocol
        runtestprotocol(item, nextitem=nextitem)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\runner.py", line 79, in runtestprotocol
        reports.append(call_and_report(item, "call", log))
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\runner.py", line 137, in call_and_report
        hook.pytest_runtest_logreport(report=report)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 745, in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 339, in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 334, in <lambda>
        _MultiCall(methods, kwargs, hook.spec_opts).execute()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 614, in execute
        res = hook_impl.function(*args)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\terminal.py", line 207, in pytest_runtest_logreport
        self.write_fspath_result(rep.nodeid, letter)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\terminal.py", line 123, in write_fspath_result
        self._tw.write(res)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 198, in write
        write_out(self._file, markupmsg)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 333, in write_out
        fil.write(msg)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 40, in write
        self.__convertor.write(text)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 141, in write
        self.write_and_convert(text)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 169, in write_and_convert
        self.write_plain_text(text, cursor, len(text))
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 175, in write_plain_text
        self.wrapped.flush()
    OSError: [WinError 87] Paramètre incorrect
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\main.py", line 111, in wrap_session
        config.notify_exception(excinfo, config.option)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\config.py", line 923, in notify_exception
        excinfo=excinfo)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 745, in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 339, in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 334, in <lambda>
        _MultiCall(methods, kwargs, hook.spec_opts).execute()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 614, in execute
        res = hook_impl.function(*args)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\terminal.py", line 164, in pytest_internalerror
        self.write_line("INTERNALERROR> " + line)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\terminal.py", line 145, in write_line
        self.ensure_newline()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\terminal.py", line 136, in ensure_newline
        self._tw.line()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 203, in line
        self.write('\n')
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 198, in write
        write_out(self._file, markupmsg)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 333, in write_out
        fil.write(msg)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 40, in write
        self.__convertor.write(text)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 141, in write
        self.write_and_convert(text)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 169, in write_and_convert
        self.write_plain_text(text, cursor, len(text))
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 174, in write_plain_text
        self.wrapped.write(text[start:end])
    OSError: [WinError 87] Paramètre incorrect
    
    During handling of the above exception, another exception occurred:
    
    Traceback (most recent call last):
      File "D:\Coding\Languages\Python\envs\py36\Scripts\pytest-script.py", line 5, in <module>
        sys.exit(pytest.main())
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\config.py", line 57, in main
        return config.hook.pytest_cmdline_main(config=config)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 745, in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 339, in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 334, in <lambda>
        _MultiCall(methods, kwargs, hook.spec_opts).execute()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 614, in execute
        res = hook_impl.function(*args)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\main.py", line 127, in pytest_cmdline_main
        return wrap_session(config, _main)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\main.py", line 122, in wrap_session
        exitstatus=session.exitstatus)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 745, in __call__
        return self._hookexec(self, self._nonwrappers + self._wrappers, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 339, in _hookexec
        return self._inner_hookexec(hook, methods, kwargs)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 334, in <lambda>
        _MultiCall(methods, kwargs, hook.spec_opts).execute()
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 613, in execute
        return _wrapped_call(hook_impl.function(*args), self.execute)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\vendored_packages\pluggy.py", line 250, in _wrapped_call
        wrap_controller.send(call_outcome)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\_pytest\terminal.py", line 359, in pytest_sessionfinish
        self._tw.line("")
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 203, in line
        self.write('\n')
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 198, in write
        write_out(self._file, markupmsg)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\py\_io\terminalwriter.py", line 333, in write_out
        fil.write(msg)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 40, in write
        self.__convertor.write(text)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 141, in write
        self.write_and_convert(text)
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 169, in write_and_convert
        self.write_plain_text(text, cursor, len(text))
      File "D:\Coding\Languages\Python\envs\py36\lib\site-packages\colorama\ansitowin32.py", line 174, in write_plain_text
        self.wrapped.write(text[start:end])
    OSError: [WinError 87] Paramètre incorrect
    Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>
    OSError: [WinError 87] Paramètre incorrect6
    
    opened by MatthieuDartiailh 10
  • Rename .closed property to avoid recursion

    Rename .closed property to avoid recursion

    Re: issue #196, this PR changes one aspect of #164 that was causing me problems.

    When using autoreset=True, this check seems to happen over and over. This method is calling itself, since StreamWrapper can be the stream.

    Adding a print statement here:

    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    Checking closure...
    
    

    So we basically have a name collision. In order to avoid that I've renamed the StreamWrapper.closed property to .is_closed. I'm happy to name it something else, or turn it back into a method instead of a property.

    opened by bbayles 10
  • colorama doesn't play well with pytest

    colorama doesn't play well with pytest

    When I run tests on a package using colorama I get this lovely traceback:

    Error in atexit._run_exitfuncs:
    Traceback (most recent call last):
      File "/usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7/lib/python2.7/atexit.py", line 24, in _run_exitfuncs
        func(*targs, **kargs)
      File "/usr/local/lib/python2.7/site-packages/colorama/initialise.py", line 19, in reset_all
        AnsiToWin32(orig_stdout).reset_all()
      File "/usr/local/lib/python2.7/site-packages/colorama/ansitowin32.py", line 67, in __init__
        strip = conversion_supported or not is_a_tty(wrapped)
      File "/usr/local/lib/python2.7/site-packages/colorama/ansitowin32.py", line 17, in is_a_tty
        return hasattr(stream, 'isatty') and stream.isatty()
    ValueError: I/O operation on closed file
    Error in sys.exitfunc:
    

    Removing colorama fixes the problem...

    opened by rjmoggach 9
  • replace tox.ini with pyproject.toml

    replace tox.ini with pyproject.toml

    See https://tox.wiki/en/latest/example/basic.html?highlight=pyproject#pyproject-toml-tox-legacy-ini

    opened by eine 0
  • Add use of release candidate versions to the Release Checklist

    Add use of release candidate versions to the Release Checklist

    Release checklist lives in README-hacking

    merge-for-next-release 
    opened by tartley 0
  • [BUG] Unicode encode error with Gitbash

    [BUG] Unicode encode error with Gitbash

    Hi,

    I came accross a strange behaviour when using colorama with in Gitbash.

    Here is a test file :

    import colorama
    
    print("\N{Heavy Check Mark} check mark")
    

    Standard run is OK :

    $ python test_colorama.py
    ✔ check mark
    

    But stderr is not empty (we get an error) when printing into a file :

    $ python test_colorama.py > output.txt
    Traceback (most recent call last):
      File "test_colorama.py", line 3, in <module>
        print("\N{Heavy Check Mark} check mark")
      File "C:\[...]\.venv\lib\encodings\cp1252.py", line 19, in encode
        return codecs.charmap_encode(input,self.errors,encoding_table)[0]
    UnicodeEncodeError: 'charmap' codec can't encode character '\u2714' in position 0: character maps to <undefined> 
    
    opened by VinceCabs 5
  • 0.4.4: pytest is failing

    0.4.4: pytest is failing

    I'm trying to package your module as an rpm package. So I'm using the typical build, install and test cycle used on building packages from non-root account.

    • "setup.py build"
    • "setup.py install --root </install/prefix>"
    • "pytest with PYTHONPATH pointing to sitearch and sitelib inside </install/prefix>

    Looks like it colorama.tests module is not installed and it is kind of assumption that tested will be source tree and not what actiually is installed (which is very untypical)

    + PYTHONPATH=/home/tkloczko/rpmbuild/BUILDROOT/python-colorama-0.4.4-3.fc35.x86_64/usr/lib64/python3.8/site-packages:/home/tkloczko/rpmbuild/BUILDROOT/python-colorama-0.4.4-3.fc35.x86_64/usr/lib/python3.8/site-packages
    + /usr/bin/pytest -ra
    =========================================================================== test session starts ============================================================================
    platform linux -- Python 3.8.12, pytest-6.2.5, py-1.10.0, pluggy-0.13.1
    benchmark: 3.4.1 (defaults: timer=time.perf_counter disable_gc=False min_rounds=5 min_time=0.000005 max_time=1.0 calibration_precision=10 warmup=False warmup_iterations=100000)
    Using --randomly-seed=1015702682
    rootdir: /home/tkloczko/rpmbuild/BUILD/colorama-0.4.4
    plugins: forked-1.3.0, shutil-1.7.0, virtualenv-1.7.0, expect-1.1.0, flake8-1.0.7, timeout-1.4.2, betamax-0.8.1, freezegun-0.4.2, aspectlib-1.5.2, toolbox-0.5, rerunfailures-9.1.1, requests-mock-1.9.3, cov-2.12.1, flaky-3.7.0, benchmark-3.4.1, xdist-2.3.0, pylama-7.7.1, datadir-1.3.1, regressions-2.2.0, cases-3.6.3, xprocess-0.18.1, black-0.3.12, anyio-3.3.0, asyncio-0.15.1, trio-0.7.0, subtests-0.5.0, isort-2.0.0, hypothesis-6.14.6, mock-3.6.1, profiling-1.7.0, randomly-3.8.0, Faker-8.12.1, nose2pytest-1.0.8, pyfakefs-4.5.1, tornado-0.8.1, twisted-1.13.3
    collected 0 items / 5 errors
    
    ================================================================================== ERRORS ==================================================================================
    _______________________________________________________________ ERROR collecting colorama/tests/ansi_test.py _______________________________________________________________
    ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/colorama-0.4.4/colorama/tests/ansi_test.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    /usr/lib64/python3.8/importlib/__init__.py:127: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    E   ModuleNotFoundError: No module named 'colorama.tests'
    ___________________________________________________________ ERROR collecting colorama/tests/ansitowin32_test.py ____________________________________________________________
    ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/colorama-0.4.4/colorama/tests/ansitowin32_test.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    /usr/lib64/python3.8/importlib/__init__.py:127: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    E   ModuleNotFoundError: No module named 'colorama.tests'
    ____________________________________________________________ ERROR collecting colorama/tests/initialise_test.py ____________________________________________________________
    ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/colorama-0.4.4/colorama/tests/initialise_test.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    /usr/lib64/python3.8/importlib/__init__.py:127: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    E   ModuleNotFoundError: No module named 'colorama.tests'
    ______________________________________________________________ ERROR collecting colorama/tests/isatty_test.py ______________________________________________________________
    ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/colorama-0.4.4/colorama/tests/isatty_test.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    /usr/lib64/python3.8/importlib/__init__.py:127: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    E   ModuleNotFoundError: No module named 'colorama.tests'
    _____________________________________________________________ ERROR collecting colorama/tests/winterm_test.py ______________________________________________________________
    ImportError while importing test module '/home/tkloczko/rpmbuild/BUILD/colorama-0.4.4/colorama/tests/winterm_test.py'.
    Hint: make sure your test modules/packages have valid Python names.
    Traceback:
    /usr/lib64/python3.8/importlib/__init__.py:127: in import_module
        return _bootstrap._gcd_import(name[level:], package, level)
    E   ModuleNotFoundError: No module named 'colorama.tests'
    ========================================================================= short test summary info ==========================================================================
    ERROR colorama/tests/ansi_test.py
    ERROR colorama/tests/ansitowin32_test.py
    ERROR colorama/tests/initialise_test.py
    ERROR colorama/tests/isatty_test.py
    ERROR colorama/tests/winterm_test.py
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 5 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    ============================================================================ 5 errors in 0.34s =============================================================================
    pytest-xprocess reminder::Be sure to terminate the started process by running 'pytest --xkill' if you have not explicitly done so in your fixture with 'xprocess.getinfo(<process_name>).terminate()'.
    
    opened by kloczek 0
  • Colorama does not work with the logging module on Windows

    Colorama does not work with the logging module on Windows

    I am using colorama for coloured terminal output on Windows with custom ANSI escape sequences in a medium size library that I currently develop. I noticed that this works well for regular prints, but not for logging output. While prints are coloured correctly, log messages still display the raw escape sequences on Windows. Is this a known issue? Can it be mitigated with special configuration?

    opened by mara004 0
  • Added check to ensure init() will only have any effect in Windows.

    Added check to ensure init() will only have any effect in Windows.

    Much like #304, I am also experiencing issues because of the not-quite-true nature of that line from the docs that carltongibson quoted.

    On other platforms, calling init() has no effect

    This is untrue when running in Linux within a Docker container, because even if you don't pass strip=True to init(), it'll still act like you did because in Docker, sys.stderr isn't a tty. It's a file descriptor that prints to a special log file which you can follow to get output that looks like a tty, but isatty() returns False. This forces strip=True, do to the if strip is None check in the AnsiToWin32 constructor, which activates the AnsiToWin32 wrapper even though the code isn't running on Windows. This completely breaks the colored output of all logs coming out of the Docker container.

    This pull request makes it 100% certain that Colorama won't screw around with sys.stderr or sys.stdout unless the program is actually running on Windows. Libraries like StructLog already wrap their call to colorama.init() in such a check, so I figure that Colorama itself should be doing this.

    requires-thought 
    opened by coredumperror 3
  • Add ability to convert strings without writing to console

    Add ability to convert strings without writing to console

    Creating a convert(string: str) global function would make certain programs easier.

    I usually code Colorama into a Python package for Windows support. I find that I have to write an initialize script in __init__.py because it seems unnecessary to init() and deinit() every time. This convert function would fix that.

    • It wouldn't rewrite sys.stdout / err
    • It wouldn't be a part of a class, though it might implement AnsiToWin32
    • It would only take one required argument, string (this leaves room for configuration)

    Some examples of this used:

    from colorama import convert
    
    def cli():
      print(convert("\033[31mHello, world!\033[0m"))
    
    if __name__ == "__main__":
      cli()
    
    opened by BD103 4
  • init(autoreset=True) is disabling colors and Fore.WHITE is grey

    init(autoreset=True) is disabling colors and Fore.WHITE is grey

    Hello,

    I've search for people getting the same errors has me, but I didn't find any related issues. I'm using PyCharm 2021.1.3 (latest) on Windows 10 and when I use the init() command with autoreset=True, there is no color at all.

    from colorama import Fore, Style, init
    init(autoreset=True)
    

    The second issue, I ran into, is that Fore.WHITEactually renders as grey: image

    The other lines are using regular print() Here is the code: print(Fore.WHITE, "AAAAAAAAAAAAAA", Style.RESET_ALL, sep='')

    The behavior is the same with and without the init() command.

    opened by h4knet 0
  • Issue on Windows 10 CMD and Poweshell

    Issue on Windows 10 CMD and Poweshell

      File "D:\x\run.py", line 164, in run_sequential
        bpar = tqdm.tqdm(total=args.t_max)
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\tqdm\std.py", line 1086, in __init__
        self.refresh(lock_args=self.lock_args)
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\tqdm\std.py", line 1380, in refresh
        self.display()
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\tqdm\std.py", line 1514, in display
        self.sp(self.__repr__() if msg is None else msg)
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\tqdm\std.py", line 335, in print_status
        fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\tqdm\std.py", line 328, in fp_write
        fp.write(_unicode(s))
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\tqdm\utils.py", line 223, in inner
        return func(*args, **kwargs)
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\colorama\ansitowin32.py", line 41, in write
        self.__convertor.write(text)
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\colorama\ansitowin32.py", line 162, in write
        self.write_and_convert(text)
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\colorama\ansitowin32.py", line 190, in write_and_convert
        self.write_plain_text(text, cursor, len(text))
      File "C:\Users\x\anaconda3\envs\py37\lib\site-packages\colorama\ansitowin32.py", line 195, in write_plain_text
        self.wrapped.write(text[start:end])
    OSError: [WinError 1] Incorrect function
    

    Does anyone know what is wrong?

    opened by GoingMyWay 4
  • Doesn't work when multiple packages are imported

    Doesn't work when multiple packages are imported

    So I've noticed that when using colorama as a sole package in my script its outputting the colours properly. But when I import multiple packages, it doesn't output any colour.

    FYI: I'm using Terminal, OS: Mac OS(Big Sur)

    opened by Nakul93 1
Owner
Jonathan Hartley
Made out of meat.
Jonathan Hartley
Rich is a Python library for rich text and beautiful formatting in the terminal.

Rich 中文 readme • lengua española readme • Läs på svenska Rich is a Python library for rich text and beautiful formatting in the terminal. The Rich API

Will McGugan 30.4k Oct 24, 2021
Python Command-line Application Tools

Clint: Python Command-line Interface Tools Clint is a module filled with a set of awesome tools for developing commandline applications. C ommand L in

Kenneth Reitz Archive 57 Oct 12, 2021
A cross platform package to do curses-like operations, plus higher level APIs and widgets to create text UIs and ASCII art animations

ASCIIMATICS Asciimatics is a package to help people create full-screen text UIs (from interactive forms to ASCII animations) on any platform. It is li

null 2.8k Oct 23, 2021
A simple terminal Christmas tree made with Python

Python Christmas Tree A simple CLI Christmas tree made with Python Installation Just clone the repository and run $ python terminal_tree.py More opti

Francisco B. 34 Oct 6, 2021
Python library that measures the width of unicode strings rendered to a terminal

Introduction This library is mainly for CLI programs that carefully produce output for Terminals, or make pretend to be an emulator. Problem Statement

Jeff Quast 250 Oct 15, 2021
Color text streams with a polished command line interface

colout(1) -- Color Up Arbitrary Command Output Synopsis colout [-h] [-r RESOURCE] colout [-g] [-c] [-l min,max] [-a] [-t] [-T DIR] [-P DIR] [-d COLORM

nojhan 1.1k Sep 28, 2021
Cleo allows you to create beautiful and testable command-line interfaces.

Cleo Create beautiful and testable command-line interfaces. Cleo is mostly a higher level wrapper for CliKit, so a lot of the components and utilities

Sébastien Eustace 763 Oct 15, 2021
Typer, build great CLIs. Easy to code. Based on Python type hints.

Typer, build great CLIs. Easy to code. Based on Python type hints. Documentation: https://typer.tiangolo.com Source Code: https://github.com/tiangolo/

Sebastián Ramírez 6.5k Oct 22, 2021
sane is a command runner made simple.

sane is a command runner made simple.

Miguel M. 14 Jul 24, 2021
plotting in the terminal

bashplotlib plotting in the terminal what is it? bashplotlib is a python package and command line tool for making basic plots in the terminal. It's a

Greg Lamp 1.6k Oct 17, 2021
Library for building powerful interactive command line applications in Python

Python Prompt Toolkit prompt_toolkit is a library for building powerful interactive command line applications in Python. Read the documentation on rea

prompt-toolkit 7.3k Oct 23, 2021
Textual is a TUI (Text User Interface) framework for Python using Rich as a renderer.

Textual is a TUI (Text User Interface) framework for Python using Rich as a renderer. The end goal is to be able to rapidly create rich termin

Will McGugan 5.8k Oct 17, 2021
Cement is an advanced Application Framework for Python, with a primary focus on CLI

Cement Framework Cement is an advanced Application Framework for Python, with a primary focus on Command Line Interfaces (CLI). Its goal is to introdu

Data Folk Labs, LLC 1k Oct 25, 2021
Pythonic command line arguments parser, that will make you smile

docopt creates beautiful command-line interfaces Video introduction to docopt: PyCon UK 2012: Create *beautiful* command-line interfaces with Python N

null 7.5k Oct 25, 2021
emoji terminal output for Python

Emoji Emoji for Python. This project was inspired by kyokomi. Example The entire set of Emoji codes as defined by the unicode consortium is supported

Taehoon Kim 1.3k Oct 16, 2021
Python composable command line interface toolkit

$ click_ Click is a Python package for creating beautiful command line interfaces in a composable way with as little code as necessary. It's the "Comm

The Pallets Projects 11.5k Oct 24, 2021
Python and tab completion, better together.

argcomplete - Bash tab completion for argparse Tab complete all the things! Argcomplete provides easy, extensible command line tab completion of argum

Andrey Kislyuk 991 Oct 22, 2021
Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object.

Python Fire Python Fire is a library for automatically generating command line interfaces (CLIs) from absolutely any Python object. Python Fire is a s

Google 20.3k Oct 24, 2021
Command line animations based on the state of the system

shell-emotions Command line animations based on the state of the system for Linux or Windows 10 The ascii animations were created using a modified ver

Simon Malave 61 Oct 21, 2021