Simple cross-platform colored terminal text in Python

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.
Comments
  • Added FORCE_COLOR and NO_COLOR environment variables

    Added FORCE_COLOR and NO_COLOR environment variables

    This patch add support for the FORCE_COLOR and NO_COLOR environment variables which are a de-facto standard for overriding automatic behaviour in circumstances where colors are required in redirected (non-TTY) output streams, or if colors are required to be removed in non-redirected (TTY) output streams.

    0.4.5 
    opened by jhol 52
  • 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
  • Yet another attempt at supporting Windows 10's ANSI/VT console

    Yet another attempt at supporting Windows 10's ANSI/VT console

    This time I'm properly using ENABLE_VIRTUAL_TERMINAL_PROCESSING which is what really controls this. I enable it when first needed and disable it on atexit. Also, instead of checking for Windows versions, I check that enabling ENABLE_VIRTUAL_TERMINAL_PROCESSING works (Probably needs additional testing to make sure this doesn't unexpectedly break).

    One obvious benefit is that Windows 10, since the creators update, also implements 256-bit color and 24-color escapes. But there definitely may be many more codes which are supported by Windows but not by colorama.

    Note that cmd has some weird behavior with this flag. It enables it when it runs, disables it when it invokes a program, and doesn't disable it when it exits. This might make you think it only works in PowerShell, which simply enables it and leaves it on (This behavior may of course change in future Windows versions).

    Should be reviewed

    • [ ] I choose to enable this in AnsiToWin32 since I remember some Python libraries that use it directly and completely bypass init (For example py (Used by pytest) and click).
    • [ ] I'm resetting _atexit_registered once it's called from atexit, so that in case some code re-enables this during atexit, we will re-register the callback so it will be called again to cleanup.
    • [ ] The dodgy conditions for strip/convert, they are so easy to get wrong. Please check and double check me.
    • [ ] And, of course, this should really be tested by other Windows users. On both Windows 10 that supports this, and older Windows versions. Maybe while using other libraries that use colorama.

    Example

    import sys
    import colorsys
    import colorama
    colorama.init()
    
    
    for i in xrange(256):
        color = colorsys.hsv_to_rgb(i/255., 1, 1)
        color = int(color[0] * 255), int(color[1] * 255), int(color[2] * 255)
        sys.stdout.write('\x1b[48;2;{0};{1};{2}m \x1b[0m'.format(*color))
    sys.stdout.write('\n')
    

    image

    Previous/Other Attempts

    https://github.com/tartley/colorama/pull/133 https://github.com/tartley/colorama/pull/105

    0.4.6 
    opened by segevfiner 24
  • Update package metadata

    Update package metadata

    Background

    Hello there! The Python packaging ecosystem has standardized on the interface for build backends (PEP 517/PEP 660) and the format for metadata declaration (PEP 621/PEP 631). As a result, the execution of setup.py files is now heavily discouraged.

    So, I'm spending my free time updating important projects so that they are modernized and set an example for others 😄

    Summary of changes

    This implements PEP 621, obviating the need for setup.py, setup.cfg, and MANIFEST.in. The build backend hatchling (of which I am a maintainer) is quite stable and actively developed, the only reason the version is 0.x is because 1.0.0 will drop support for Python 2. It's also on the major distribution channels such as Debian, Fedora, Arch Linux, conda-forge, Nixpkgs, etc.

    Other projects have done this such as pipx, tox, all Datadog Agent integrations, etc.

    In comparison to setuptools, Hatchling has reproducible builds, supports the modern PEP 660 editable installation standard, has a more intuitive plugin system, and the codebase is an order of magnitude smaller thus making it more auditable and less prone to bugs (setuptools is based on a deprecated standard library module that it now must vendor).

    Notes

    • Similar to https://github.com/tartley/colorama/pull/228, this also drops support for EOL Python 3.x versions since hatchling and other build backends like setuptools have already done so. This will not break anything because pip only looks for version candidates that satisfy the requires-python field. Here are stats for the curious: https://pypistats.org/packages/colorama
    • The source distributions on PyPI are erroneously shipping a build artifact *.egg-info from pip install -e .; this is now fixed: c
    0.4.6 
    opened by ofek 17
  • 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
  • Get rid of `hatchling` and return back to `setuptools`

    Get rid of `hatchling` and return back to `setuptools`

    In PR #338 setuptools was replaced by hatchling by its maintainer, who obviously has conflict of interest between promoting his software and doing the best for this project as a contributor. The PR was sent 2022-03-27, setuptools 61.2.0 with usable support of PEP 621 was released the same day (setuptools has started supporting PEP 621 in 61.0.0 released on 2022-03-24, but there were issues, so I usually set >=61.2 in my projects).

    We need:

    1. a lightweight solution
    2. requiring no additional dependencies

    setuptools is the de-facto standard and so should be already installed. I think we should replace hatchling with setuptools. If setuptools seems to be too heavy, the next alternative is flit. All of them support PEP 621, so the changes in the pyproject.toml should be minimal.

    And yet another opinion: PEP 517 was a big mistake because instead of one single build system (setuptools) we now have to install a whole zoo of build systems (flit_core, poetry_core has long become a mandatory minimum with its own very loyal adepts (worth noting: flit really works much faster than setuptools, so using flit may be justified in some cases), and now hatchling and maturin (an extremily heavy build system written in Rust, even though setuptools-rust plugin exists for this purpose) seems to be added to it) doing the same things but created and promoted out of "not-invented-here" syndrome.

    opened by KOLANICH 12
  • 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 12
  • 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
  • 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
  • Permission Error: [WinError 31] A device attached to the system is not functioning

    Permission Error: [WinError 31] A device attached to the system is not functioning

    We have a few users that are encountering the above error:

      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\torch\hub.py", line 485, in download_url_to_file
        pbar.update(len(buffer))
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\tqdm\std.py", line 1256, in update
        self.refresh(lock_args=self.lock_args)
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\tqdm\std.py", line 1361, in refresh
        self.display()
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\tqdm\std.py", line 1509, in display
        self.sp(self.__str__() if msg is None else msg)
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\tqdm\std.py", line 350, in print_status
        fp_write('\r' + s + (' ' * max(last_len[0] - len_s, 0)))
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\tqdm\std.py", line 343, in fp_write
        fp.write(_unicode(s))
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\tqdm\utils.py", line 145, in inner
        return func(*args, **kwargs)
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\colorama\ansitowin32.py", line 47, in write
        self.__convertor.write(text)
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\colorama\ansitowin32.py", line 177, in write
        self.write_and_convert(text)
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\colorama\ansitowin32.py", line 205, in write_and_convert
        self.write_plain_text(text, cursor, len(text))
      File "D:\INSTALL\stable-diffusion-ui\stable-diffusion\env\Lib\site-packages\colorama\ansitowin32.py", line 210, in write_plain_text
        self.wrapped.write(text[start:end])
    PermissionError: [WinError 31] A device attached to the system is not functioning
    

    Python is started from a cmd window. The colorama version is 0.4.6 on Windows 10. The script is run as normal user.

    Do you have any idea why this might happen?

    opened by JeLuF 2
  • sys.stderr trunc traceback, colorama problem

    sys.stderr trunc traceback, colorama problem

    I submitted an issue in this repository that use colorama as dependency: 'https://github.com/Delgan/loguru', this is the link of the issue https://github.com/Delgan/loguru/issues/754#issue-1468262003, i can confirm @Delgan is right (https://github.com/Delgan/loguru/issues/754#issuecomment-1331166181), with the latest version 0.4.6 the message in console is trunced, while with 0.4.5 version all works great

    opened by zN3utr4l 3
  • IOError for 0.4.6

    IOError for 0.4.6

    my colorama version is 0.4.6 and OS is windows 10 pro

    @njsmith sir, i got IOError issue at 0.4.6 version

    here is Traceback

    Traceback (most recent call last):
      File "C:\Python27\lib\runpy.py", line 174, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
      File "C:\Python27\lib\runpy.py", line 72, in _run_code
        exec code in run_globals
      File "c:\Users\103452\.vscode\extensions\ms-python.python-2022.2.1924087327\pythonFiles\lib\python\debugpy\__main__.py", line 45, in <module>
        cli.main()
      File "c:\Users\103452\.vscode\extensions\ms-python.python-2022.2.1924087327\pythonFiles\lib\python\debugpy/../debugpy\server\cli.py", line 444, in main
        run()
      File "c:\Users\103452\.vscode\extensions\ms-python.python-2022.2.1924087327\pythonFiles\lib\python\debugpy/../debugpy\server\cli.py", line 331, in run_module
        run_module_as_main(target_as_str, alter_argv=True)
      File "C:\Python27\lib\runpy.py", line 174, in _run_module_as_main
        "__main__", fname, loader, pkg_name)
      File "C:\Python27\lib\runpy.py", line 72, in _run_code
        exec code in run_globals
      File "C:\Python27\lib\site-packages\flask\__main__.py", line 15, in <module>
        main(as_module=True)
      File "C:\Python27\lib\site-packages\flask\cli.py", line 967, in main
        cli.main(args=sys.argv[1:], prog_name="python -m flask" if as_module else None)
      File "C:\Python27\lib\site-packages\flask\cli.py", line 586, in main
        return super(FlaskGroup, self).main(*args, **kwargs)
      File "C:\Python27\lib\site-packages\click\core.py", line 782, in main
        rv = self.invoke(ctx)
      File "C:\Python27\lib\site-packages\click\core.py", line 1259, in invoke
        return _process_result(sub_ctx.command.invoke(sub_ctx))
      File "C:\Python27\lib\site-packages\click\core.py", line 1066, in invoke
        return ctx.invoke(self.callback, **ctx.params)
      File "C:\Python27\lib\site-packages\click\core.py", line 610, in invoke
        return callback(*args, **kwargs)
      File "C:\Python27\lib\site-packages\click\decorators.py", line 73, in new_func
        return ctx.invoke(f, obj, *args, **kwargs)
      File "C:\Python27\lib\site-packages\click\core.py", line 610, in invoke
        return callback(*args, **kwargs)
        show_server_banner(get_env(), debug, info.app_import_path, eager_loading)
      File "C:\Python27\lib\site-packages\flask\cli.py", line 670, in show_server_banner
        click.echo(message)
      File "C:\Python27\lib\site-packages\click\utils.py", line 267, in echo
        file = auto_wrap_for_ansi(file)
      File "C:\Python27\lib\site-packages\click\_compat.py", line 704, in auto_wrap_for_ansi
        ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)
      File "C:\Python27\lib\site-packages\colorama\ansitowin32.py", line 101, in __init__
        system_has_native_ansi = not on_windows or enable_vt_processing(fd)
      File "C:\Python27\lib\site-packages\colorama\winterm.py", line 183, in enable_vt_processing
        handle = get_osfhandle(fd)
    IOError: [Errno 9] Bad file descriptor
    
    opened by 841020 4
  • ANSI Codes inserted, but not interpreted when running in VS 2019 debugger

    ANSI Codes inserted, but not interpreted when running in VS 2019 debugger

    I can see that the escape sequences are being added as expected when I use things like Fore.RED and whatnot, but instead of changing the colors, they just come out as the sequences.

    It works every other way I've tried. Double clicking the script and running it through the python console, using cmd or powershell, and even copying and pasting the code into VS's interactive python console window all work fine. Just not when I run it through the debugger.

    Here's some quick code that I used to demonstrate:

    from colorama import just_fix_windows_console
    just_fix_windows_console()
    from colorama import Fore, Back, Style
    
    print(Fore.RED + "Test text" + Style.RESET_ALL)
    print("For compariston")
    

    Here's a link to imgur showing the difference.

    Is there some setting I need to change to get it to work properly? Or is this just some VS quirk and I'm out of luck?

    opened by talbertine 1
  • Unexpected background color rendered in terminal

    Unexpected background color rendered in terminal

    import colorama
    from contextlib import contextmanager
    
    
    b = "type: <\x1b[39m\x1b[38;5;100mclass\x1b[39m\x1b[38;5;245m \x1b[39m\x1b[38;5;166m'\x1b[39m\x1b[38;5;32mdict\x1b[39m\x1b[38;5;36m'\x1b[39m\x1b[38;5;36m>\x1b[39m"
    
    
    @contextmanager
    def supportTerminalColorsInWindows():
        colorama.init()
        yield
        colorama.deinit()
    
    
    print(b)
    
    with supportTerminalColorsInWindows():
        print(b)
    

    Running the above code gives an unexpected result shown below on both PowerShell and CMD.

    image image

    opened by RoryLiang 0
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 41.4k Jan 2, 2023
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. 64 Dec 27, 2022
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.6k Jan 2, 2023
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 305 Dec 25, 2022
A thin, practical wrapper around terminal capabilities in Python

Blessings Coding with Blessings looks like this... from blessings import Terminal t = Terminal() print(t.bold('Hi there!')) print(t.bold_red_on_brig

Erik Rose 1.4k Jan 7, 2023
Terminalcmd - a Python library which can help you to make your own terminal program with high-intellegence instruments

Terminalcmd - a Python library which can help you to make your own terminal program with high-intellegence instruments, that will make your code clear and readable.

Dallas 0 Jun 19, 2022
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.7k Jan 2, 2023
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 17k Jan 2, 2023
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 Dec 21, 2022
sane is a command runner made simple.

sane is a command runner made simple.

Miguel M. 22 Jan 3, 2023
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 23.6k Dec 31, 2022
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 13.3k Dec 31, 2022
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 8.1k Dec 30, 2022
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 1.1k Jan 8, 2023
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 10.1k Jan 2, 2023
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 82 Dec 28, 2022
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 1.1k Dec 31, 2022
Corgy allows you to create a command line interface in Python, without worrying about boilerplate code

corgy Elegant command line parsing for Python. Corgy allows you to create a command line interface in Python, without worrying about boilerplate code.

Jayanth Koushik 7 Nov 17, 2022
prompt_toolkit is a 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 8.1k Jan 4, 2023