Giter Club home page Giter Club logo

colorama's Introduction

⭐ About me ⭐

An experienced back-end generalist, specializing in Python.

I created Colorama, the world's 28th most popular Python library, present at international conferences like PyCon, and am a nominated Fellow of the Python Software Foundation. I make continual open source contributions, e.g. this recent drive-by analysis and fixes for static web site generator Nikola, or this page of ModernGL docs, which I created from scratch to help me understand a fiddly API concept, using plain language but without skirting details.

I consult and mentor in Test-Driven Development (TDD), favoring the "London School" and "double loop" variants, when appropriate. I was tech reviewer on O'Reilly's Test Driven Development with Python, published on testing in Python Magazine, and landed modest CPython patches in unitttest.

I believe in radically jovial relationships, taking pride in our humane treatment of one another, and real talk. Great teams create great individuals, not the other way around.

colorama's People

Contributors

3tilley avatar andyneff avatar cclauss avatar clenk avatar delgan avatar digwanderlust avatar hoefling avatar hugovk avatar jdufresne avatar jszakmeister avatar jurko-gospodnetic avatar merriam avatar mondeja avatar msabramo avatar njsmith avatar odidev avatar ofek avatar paweljasinski avatar rdil avatar remram44 avatar scop avatar segevfiner avatar svisser avatar tartley avatar timgates42 avatar timokasse avatar veleek avatar weinimo avatar wiggin15 avatar zearin 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  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

colorama's Issues

Color Style not reset after RESET when using LIGHT_EX colors in Windows

When printing a Fore.LIGHT*_EX color and attempting to use Fore.RESET, in windows the colors stay "light" instead of returning to their normal state. A RESET_ALL or Style Change is needed to manually fix it.

In Linux, it behaves as expected.
linux

But in Windows 7, it does not
windows
It's a little hard to see, but on the first line the d and e are bright, When only the d should be bright, and on the second line, the b, c, d, and e are all bright, when again, only the d should be bright.

colorama.init() interferes with KeyboardInterrupt.

Colorama interfers with keyboard interrupts.

The following code doesn't work as expected, after calling colorama.init().

import colorama
from colorama import Fore

colorama.init()

while True:

    try:
        line = raw_input(':')

        if not line:
            break

        print Fore.RED + line + Fore.RESET

    except KeyboardInterrupt:
        print 'I wan\'t to quit, peacefully!'   # <----- this line isn't hit, after colorama.init() is called.

sys.stdout interface changes after wrapping

Reported by [email protected], Feb 10 (5 days ago)
Somewhat related to Issue 41, but if you have replaced sys.stdout with something else (like StringIO in order to capture output for unit testing purposes), then the wrapping that colorama does exposes an interface that differs from that of the object you set sys.stdout to. Namely in the case of StringIO, it has a getvalue() method to get what was written to it.

After calling colorama.init, the object set to sys.stdout no longer has this method.

What steps will reproduce the problem?

  1. set sys.stdio=StringIO
  2. call colorama.init(strip=True,convert=False)
  3. try to call sys.stdio.getvalue()

What is the expected output?
An empty string on the console.

What do you see instead?
An error message about sys.stdio not having a 'getvalue' method.

What version of the product are you using? On what operating system?
'0.2.5'
Feb 10 (5 days ago) #1 [email protected]
slight correction to code:

import StringIO
import sys
import colorama
sys.stdout = StringIO.StringIO()
colorama.init(strip=True, convert=False)
sys.stdout.getvalue()

(Issue migrated from https://code.google.com/p/colorama/issues/detail?id=64)

Report issues on Google code, not here

This project is recently migrated from Google code.

The issues list currently still resides there until I migrate it over to github.

Please report any issues there for now:

https://code.google.com/p/colorama/issues/list

Thanks.

Consider no-tty handling, again

Following issue #47, reset codes are now emitted even when redirection is taking place (i.e., no tty).
Since colorama calls reset_all when the program terminates, there is now an undesired effect when using colorama and redirection -- a reset code will be emitted along with the redirected output. See:

> python -c "import colorama; colorama.init(); print('a')" | xargs python -c "import sys; print(sys.argv)"
['-c', 'a', '\x1b[0m']

In other words, commands that take output from scripts with colorama will now get an extra ANSI reset code, which they probably don't expect.

  • The bahavior before fixing #47: On Linux when there is no tty, reset_all codes were stripped but other ANSI codes were not stripped
  • The current behavior: On Linux when there is no tty, nothing is stripped and both reset codes and other color codes are written to the redirected output
  • New, suggested behavior: On Linux when there is no tty, all ANSI codes should be stripped

Note that on Windows when there is no tty, all ANSI codes are already stripped.
@tartley noted in #47 that colorama should behave like other unix utilities (like 'ls') and output color codes only on tty. I disagreed, but I changed my mind now.

The change in the code is simple, if I'm not mistaken: change the default strip value from:

strip = conversion_supported

to

strip = conversion_supported or not is_a_tty(wrapped)

The impact is that the behavior of colorama on Linux with redirection will change.
Does this make sense? Does everyone agree that colorama should strip the color codes and the reset codes when there is no tty? Does the code change look right?
@tartley, your thoughts?

Add dummy mode

I would like to make colour output configurable in my program, so I'd love to see a dummy parameter to init() that basically disables coloring, i.e. either strips all color codes from stdout/stderr or sets all color code variables to RESET.

ANSI reset code is printed on Windows on program exit

Given the following Python file:

import colorama
colorama.init()

Running it results in this:

C:\Users\markus\tmp>python test.py
←[0m
C:\Users\markus\tmp>

This is the result of running initialise.reset_all when exiting the script. The AnsiToWin32 instance that is created isn't instructed to convert ANSI codes, so it just prints the ANSI reset code.

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.

IPython colors on Windows are weird after init()

What steps will reproduce the problem?
On a windows box:

  1. pip install ipython
  2. ipython (to open ipython shell)
  3. import colorama
  4. colorama.init()

Dorks up the prompt and a lot of other ipython output

Reported by email from briford at the domain supercowpowers.com, Aug 11, 2014
Migrated from https://code.google.com/p/colorama/issues/detail?id=58

screen shot 2014-08-11 at 2 56 30 pm


From google code user szell.andris:

Hi,

I did not find a solution but found others having the same issue:

http://comments.gmane.org/gmane.comp.python.ipython.devel/13262

Last comment suggests "colorama ... and pyreadline (which IPython does use) both try to interpret ANSI escape codes and ... they conflict in some way" [lot of text replaced by dots].

Starting 'ipython console' instead of ipython solves the garbled prompt but breaks colorama features for me. (I am using windows.)

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...

Doesn't work on IronPython

Within the colorama package, the file "initialise.py" at line 56, it should be:

on_windows = sys.platform.startswith('win') or sys.platform.startswith('cli')

instead of:

on_windows = sys.platform.startswith('win')

play nicely with other stdout/stderr wrappers

Migrated from https://code.google.com/p/colorama/issues/detail?id=41
Reported by eallik, Jan 21, 2013

Take a look at the wrapper provided at http://stackoverflow.com/a/3259271/247623 --it reliably enables Unicode output on cmd.exe; unquestionably useful. However, it turns out that colorama does not work out of the box in combination with that wrapper.

The reasons for this are:

  • first of all, colorama needs to be activated after that wrapper because the other wrapper is more low level/fundamental
  • colorama remembers the orig_stdout and orig_stderr references in its initialise.py at import time, thus, by the time init() is called, any wrappings that have taken place before import colorama and init() are effectively cancelled/ignored
  • colorama does not convert ANSI codes for streams who are not .isatty() == True; I'm not sure why such check was implemented in the first place, but it looks to me that colorama works perfectly well with streams that do not have such property.

The current workaround is to manually update orig_stdout and orig_stderr with fresh values from sys.stdout and sys.stderr respectively, and also do sys.stdout.isatty = sys.stderr.isatty = lambda: True to satisfy the is_a_tty check in ansitowin32.py. However, it would be nice if colorama did not require such workaround to compose nicely with other wrappers.

v0.3.2 crashes when clearing console on Windows7 / Python3.4

Received this helpful email:

Good day-
I have tried to use the colorama-0.3.2 on a Windows 7 PC, using Python 3.4, but my program would crash when attempting to clear the console. I examined colorama's winterm.py file and found the following pieces of problem code:


Line 111: coord_screen = win32.COORD(0,0)
Problem: There is no win32.COORD() function.
Solution: Replace line 111 with the following:
coord_screen = win32.GetConsoleScreenBufferInfo(handle).dwCursorPosition
coord_screen.Y = coord_screen.X = 0
Why: The first line gets a coordinate object; the second sets it to (0,0).

There likely is a single call that generates the coordinate object, but I don't know what that call would be, and presume I would need to import an additional library (which-ever that would be) to access that call. Instead I get an existing coordinate object and re-position it


Line 116: win32.FillConsoleOutputCharacter(handle, ' ', dw_con_size, coord_screen)
Problem: In Python 3.x, character strings are Unicode (thus 2-bytes per character), not one byte per character.
Solution: change ' ' to b' '
Why: By explicitly declaring single byte character string, the needed conversion is explicitly imposed.


Line 120: win32.SetConsoleCursorPosition(handle, (coord_screen.X, coord_screen.Y))
Problem: The console position (0,0) doesn't seem to work when setting the console cursor position.
Solution:
win32.SetConsoleCursorPosition(handle, (1,1))
Why: It appears that SetConsoleCursorPosition() uses 1-basis postioning rather than 0-basis; by explicitly moving the cursor to (1,1), the desired "set to home position" now works.


With these changes, colorama now works on my Windows PC when using Python 3.4. I do not have an installation of Python 2.x, nor do I have a non-Windows PC to test my changes, but I hope this will help correct an otherwise very useful Python library.

Regards-
Richard Miner
[email protected]

Add support for CSI n K: EL – Erase in Line

Migrated from https://code.google.com/p/colorama/issues/detail?id=30
Reported by [email protected], Oct 20, 2011

As described on Wikipedia:
"Erases part of the line. If n is zero (or missing), clear from cursor to the end of the line. If n is one, clear from cursor to beginning of the line. If n is two, clear entire line. Cursor position does not change."

What steps will reproduce the problem?

  1. print('Foo\033[1K')

What is the expected output? What do you see instead?
winterm.WinTerm.erase_line() needs to be added, which would be similar to erase_data().

What version of the product are you using? On what operating system?
c25659277b30

Finalise formal project ownership handover

@wiggin: My fingerprints are still all over this project, but I never use Windows these days, plus am now a Dad, so these days I have little time, and even less incentive, to contribute.

This ticket is my attempt to clean up any vestiges of my ownership that might make life less pleasant for @wiggin and other future contributors. Things that might need changing (let's discuss here):

  • Does it make sense for the github repo to continue to be owned by me (tartley)? Or should we change it to @wiggin15? Or should we create a new 'colorama' user or organisation to encourage contributions & group ownership? The downside of changing is that (I assume) it changes the repo URL (again.) I think it's fine as-is, but would love to hear people's thoughts.
  • Does it make sense to transfer ownership of the PyPI entry? Remind me, did I give anyone the credentials needed to make a release without my input? If not, let's fix that somehow.
  • The README lists me as the only entry under 'Contacts'. This no longer makes sense. I do occasionally get bug reports or requests for help to that address (which I try to forward on to the proper places.) Should we replace it with contact details for @wiggin15? Or just the Colorama mailing list? (PR #72 uses the mailing list)
  • Anything else?

Document API Changes in 0.3

I don't know if there were any. I wanted to update AWS CLI dependency on colorama, but I don't know what will break. Of course I could just upgrade and see what happens, but I guess it'd be nice to document it.

Highlight background of text

Using print Back.YELLOW + 'initiating connection...' will change the background of the entire line in the terminal. Is there a way to only highlight the text background?

py.test creates an environment that causes colorama to fail

Migrated from https://code.google.com/p/colorama/issues/detail?id=45
Reported by p.f.moore, Oct 3, 2013

When using py.test to run a file that imports colorama on Windows, the import fails (as far as I can tell, because the Windows standard handle does not point to a proper console)
Here's an example:

>type t.py
from pip.vendor import colorama
>python t.py >a
>type a
>py.test t.py
============================================= test session starts ============================================== platform win32 -- Python 3.3.0 -- pytest-2.4.1
collected 0 items / 1 errors

==================================================== ERRORS ==================================================== ____________________________________________ ERROR collecting t.py _____________________________________________ t.py:1: in <module>
>   from pip.vendor import colorama
pip\__init__.py:10: in <module>
>   from pip.log import logger
pip\log.py:11: in <module>
>   from pip.vendor import colorama
pip\vendor\colorama\__init__.py:1: in <module>
>   from .initialise import init, deinit, reinit
pip\vendor\colorama\initialise.py:4: in <module>
>   from .ansitowin32 import AnsiToWin32
pip\vendor\colorama\ansitowin32.py:11: in <module>
>       winterm = WinTerm()
pip\vendor\colorama\winterm.py:25: in __init__
>       self._default = win32.GetConsoleScreenBufferInfo(win32.STDOUT).wAttributes
pip\vendor\colorama\win32.py:64: in GetConsoleScreenBufferInfo
>           handle, byref(csbi))
E       ctypes.ArgumentError: argument 2: <class 'TypeError'>: expected LP_CONSOLE_SCREEN_BUFFER_INFO instance instead of pointer to CONSOLE_SCREEN_BUFFER_INFO
=========================================== 1 error in 0.74 seconds ===========================================

I'm not sure if this is a py.test bug or a colorama bug, so I have reported it to both projects. I suspect that maybe colorama should ensure on import that it does not try to initialise itself if the standard output is not suitable.

Support for python 3.2.5

from colorama import Fore, Back, Style
# ...
    print Back.YELLOW + Fore.BLACK + 'Initiating connection...' + Style.RESET_ALL
             ^
SyntaxError: invalid syntax

iPython notebook not supporting Style or autoreset

I can set the background and foreground colors in iPython notebook, but the default behavior for autoreset and style seem to not be functioning. The below screen shot from the notebook shows the steps necessary to reproduce.
bq9000_delta-sigma_analysis
This was done with ipython 3.1, which perhaps isn't really the target for colorama.

Colorama causes pylint errors in client code

I don't know if this is an issue with colorama or with pylint.

What steps will reproduce the problem?

  1. Use colorama in a project
  2. Use predefined colors
  3. Run pylint on the code

Result:
E:143,18: Instance of 'AnsiCodes' has no 'RED' member (no-member)
E:143,64: Instance of 'AnsiCodes' has no 'RESET' member (no-member)
E:157,47: Instance of 'AnsiCodes' has no 'BRIGHT' member (no-member)
E:158,45: Instance of 'AnsiCodes' has no 'RESET_ALL' member (no-member)
E:172,49: Instance of 'AnsiCodes' has no 'BRIGHT' member (no-member)
E:173,45: Instance of 'AnsiCodes' has no 'RESET_ALL' member (no-member)
E:187,49: Instance of 'AnsiCodes' has no 'BRIGHT' member (no-member)
E:188,45: Instance of 'AnsiCodes' has no 'RESET_ALL' member (no-member)

What is the expected output? What do you see instead?
Code passes the check

What version of the product are you using? On what operating system?
0.3.1 on Windows via Anaconda

Please provide any additional information below.
I found a similar issue with a patch on the Chromium project:
https://codereview.chromium.org/10202010

Reported by google code user peter.azp, Nov 12, 2014
Migrated from https://code.google.com/p/colorama/issues/detail?id=62


From Googlecode user nickjacobson:
The problem is that those attributes are dynamically set with setattr. See http://docs.pylint.org/plugins.html#example for description of this problem. To fix it, the colorama file ansi.py could be reworked to avoid use of setattr.

Control codes are visible, all output is blue

Migrated from googlecode https://code.google.com/p/colorama/issues/detail?id=66

Reported by Tayyab.Ditta, Yesterday (22 hours ago)
I have installed colorama but i get the following error when running this code:

from colorama import init
from termcolor import colored

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

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(Fore.RESET + Back.RESET + Style.RESET_ALL)
print('back to normal now')

I get this error when running the above:

Traceback (most recent call last):
  File "E:/Documents/Python/colorama.py", line 1, in <module>
    from colorama import init
  File "E:/Documents/Python\colorama.py", line 1, in <module>
    from colorama import init
ImportError: cannot import name 'init'

a way to disable scrolling with the current text buffer

(Feature request(s) submitted in an email, details below.)

Hello. I am writing a data analysis app for a local university and jazzed it up a bit with your fine module. Thanks! I thought I'd send a list, and outline a feature suggestion or two.

http://youtu.be/oKabJY-IAJI

two feature requests:

  1. way to disable scrolling with the current text buffer. I'm pretty sure there's functions for this in the windows api but I couldnt' get it sorted out and eventually gave up. But if you had an easy way to implement that in your module, I'd use it.

Similar to 1 - Way to resize the textbuffer so it's the same size as the window and (maybe?) remove the scroll bar from python console apps.
#2 isn't really a request but here's the deal, I wanted to make that bottom bar blue, and what i found was any write to the bottom right most character cell resulted in scrolling. So instead I blank the screen (with the ansi clear command) with the background set to the color I want the bottom bar to be, then I set the real page bg color and draw everywhere else, leaving only blue bar at bottom. It works but it feels clunky, so I thought if I explained the process to you maybe you had a better suggestion or you could factor that into your development somehow.

Have you thought about rolling mouse support in there too? Feels like a totally different module but it's another one I'd use a lot. I have hacked together some basic 'get the current font metrics, current window position, mouse screen position, and window client position of the mouse screen position, scaled by the font metric' sorted out... So it outputs 'mx,my = [0-80],[0-maxy]'. If this would help you let me know and I'll throw it on codepad, I'm sure you could rewrite it a lot better than my quick and dirty hack job.

btw I wrote http://store.raspberrypi.org/projects/scamp - It's an all-ascii UI to the RPI media player (using python/curses). I've had a lot of requests to port it to windows/other linux, which I don't understand since VLC is so nice but whatever, I'm thinking about doing it and if I do I'm going to use colorama for the windows side.

Thanks again for all your hard work, have a nice day and if you ever need another beta tester or just someone to hash out some 'ansi issues' with, email me any time

Matt Kimball
greyworld at host gmail with tld com.

Importing fails for python3 on Windows

Tried on both Windows 7 and Windows 8.1. Importing colorama works fine in python2.7, but not in python3.4, where it gives this error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\cygwin64\tmp\colorama\colorama\__init__.py", line 2, in <module>
    from .initialise import init, deinit, reinit
  File "C:\cygwin64\tmp\colorama\colorama\initialise.py", line 5, in <module>
    from .ansitowin32 import AnsiToWin32
  File "C:\cygwin64\tmp\colorama\colorama\ansitowin32.py", line 7, in <module>
    from .winterm import WinTerm, WinColor, WinStyle
  File "C:\cygwin64\tmp\colorama\colorama\winterm.py", line 2, in <module>
    from . import win32
  File "C:\cygwin64\tmp\colorama\colorama\win32.py", line 89, in <module>
    wintypes.c_char_p
AttributeError: 'module' object has no attribute 'c_char_p'

Don't depend to ctypes on Linux

Hi,

On CPython buildbot "FreeBSD 7.2, the compilation of the ctypes module fails. The pip module cannot be used because it imports colorama which uses ctypes for its win32 module, and the win32 module is always imported, even on Linux. IMO it would be better to not import this module on Linux to avoid the dependency to ctypes.

I also reported the issue to pip:
pypa/pip#2079

Test output on the buildbot:

FAIL: test_with_pip (test.test_venv.EnsurePipTest)

Traceback (most recent call last):
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/test/test_venv.py", line 357, in test_with_pip
with_pip=True)
subprocess.CalledProcessError: Command '['/tmp/tmp71gop0m5/bin/python', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/test/test_venv.py", line 363, in test_with_pip
self.fail(msg.format(exc, details))
AssertionError: Command '['/tmp/tmp71gop0m5/bin/python', '-Im', 'ensurepip', '--upgrade', '--default-pip']' returned non-zero exit status 1

Subprocess Output
Traceback (most recent call last):
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/runpy.py", line 170, in _run_module_as_main
"main", mod_spec)
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/ensurepip/main.py", line 4, in
ensurepip._main()
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/ensurepip/init.py", line 209, in _main
default_pip=args.default_pip,
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/ensurepip/init.py", line 116, in bootstrap
_run_pip(args + [p[0] for p in _PROJECTS], additional_paths)
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/ensurepip/init.py", line 40, in _run_pip
import pip
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/init.py", line 9, in
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/log.py", line 9, in
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/_vendor/colorama/init.py", line 2, in
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/_vendor/colorama/initialise.py", line 5, in
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/_vendor/colorama/ansitowin32.py", line 6, in
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/_vendor/colorama/winterm.py", line 2, in
File "/tmp/tmplhy261sg/pip-1.5.6-py2.py3-none-any.whl/pip/_vendor/colorama/win32.py", line 7, in
File "/usr/home/db3l/buildarea/3.x.bolen-freebsd7/build/Lib/ctypes/init.py", line 7, in
from _ctypes import Union, Structure, Array
ImportError: No module named '_ctypes'

colorama.ansi.set_title('') should (un|re)set title

I just noticed that in colorama.ansi, set_title doesn’t do anything if you give it an empty string. Therefore, if you use it in a Python program, when that program exits, the title does not return to whatever it was before. However, if I type in echo -n -e "\033]0;\007", it resets to its default value. (I’m on OS X 10.10, using Terminal.app, so the default value is simply “Terminal”.)

So, I think colorama should:

  • allow using set_title with the empty string
  • offer a keyword option (in colorama.init() or in ansi.set_title()) to unset the window title when Python exits

support context manager syntax

Reported by steve at the domain 3xile dot com, Aug 8, 2011
It'd be nice to turn colorized output on and off with with rather than either init() or writing by hand, especially when other modules want to modify sys.stdout. Here's an example implementation:

import sys
from colorama import Fore, AnsiToWin32

class ConvertedOutput(object):
    def __init__(self, *AnsiToWin32Args, **kwargs):
        self._AnsiArgs = AnsiToWin32Args
        self._set_stderr = kwargs.get('stderr', None)
    def __enter__(self):
        self._stdout = sys.stdout
        sys.stdout   = AnsiToWin32(sys.stdout, *self._AnsiArgs)
        if self._set_stderr:
            sys.stderr = AnsiToWin32(sys.stderr, *self._AnsiArgs)
    def __exit__(self, type, value, traceback):
        sys.stdout = self._stdout

And example usage:

with ConvertedOutput():
    print('%sThis text is red%s' % (Fore.RED, Fore.RESET))

print('%sThis text is surrounded by junk%s' % (Fore.RED, Fore.RESET))

Migrated from https://code.google.com/p/colorama/issues/detail?id=28&can=1

Support binary streams on Python 3

On Python 3, it is impossible to use colorama with a binary stream, such as sys.stdout.buffer, but it is necessary to use this if you need precise control over the encoding of your output.

In any case, ANSI escapes are by nature binary insertions in a binary stream, so it makes sense to support this mode.

Add support for Windows xterm emulators.

Migrated from https://code.google.com/p/colorama/issues/detail?id=16
Reported by deldie, Jul 24, 2010

What steps will reproduce the problem?

  1. Launch python.exe win32 binary under xterm, rxvt, or mintty terminal emulators for Cygwin.
  2. Execute an script with colorama.init() and ANSI escape sequences.

What is the expected output? What do you see instead?
It should show colored output, but it strips the escape sequences.
I guess it should work with the Python Cygwin port as the value of sys.platform, according to the Python docs, is 'cygwin' and not 'win32'.

What version of the product are you using? On what operating system?
The last version of colorama module, Python 2.7 Win32 (not that from the Cygwin package) and Windows XP SP3.

Please provide any additional information below.
I've resolved this adding these lines to my example code:

import os
from colorama import init

terminal = os.getenv('TERM')

if terminal is None or 'rxvt' not in terminal:
    init(autoreset=True)
else:
    init(autoreset=True, convert=False, strip=False)

print "\033[45m" "HOLA"
print "HOLA"

This example code outputs the same result either under CMD.EXE or under Cygwin default console or under rxvt terminal, only the first HOLA is magenta.

I think it would be great to support the Windows xterm emulators in colorama.

"ValueError: I/O operation on closed file" with pytest since 0.3.5

Since upgrading colorama to 0.3.5, I get the following when running pytest (on Linux):

Error in atexit._run_exitfuncs:
Traceback (most recent call last):
  File ".../python3.4/site-packages/colorama/initialise.py", line 19, in reset_all
    AnsiToWin32(orig_stdout).reset_all()
  File ".../python3.4/site-packages/colorama/ansitowin32.py", line 67, in __init__
    strip = conversion_supported or not is_a_tty(wrapped)
  File ".../python3.4/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

colorama.init() emits deprecation warning in Python 2 when using -3 flag

I've tested this particular issue with Python 2.7.9 / colorama 0.3.3 on Fedora 21 and Windows 7 x64.

C:\Python27\python.exe -3

import colorama
colorama.init()
C:\Python27\lib\site-packages\colorama\ansitowin32.py:33: DeprecationWarning: file.softspace not supported in 3.x
return getattr(self.__wrapped, name)

Can this deprecation warning be corrected?

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.

Enable Travis CI

There is already a .travis.yml but there are no travis builds yet

install colorama on python 2.7 on windows 8

Reported by rob.kelley06 @ googlecode
I am trying to install colorama on python 2.7 on windows 8

I am running the install command on administrator...

C:\Users\dianna\Desktop\outwar\colorama-0.3.3\setup.py install

i continue to get this error:

running install
running build
running build_py
error: package directory 'colorama' does not exist

any ideas?

autoreset=True appears not to work

reported by email from jason kenny via jonathan hartley (tartley)

If I write a simple program.. ie

import colorama
colorama.init(autoreset=True,strip=False,convert=False)
print colorama.Fore.RED+"hello"
print "some more"
print colorama.Fore.RESET+ "should be back to normal"

and run on windows

test.py > out.txt

I get this in out.txt

←[31mhello
some more
←[39mshould be back to normal

not the expected:

←[31mhello←[0m
←[0msome more←[0m
←[0m←[39mshould be back to normal←[0m
←[0m

Is this known?

win32 module has no attribute COORD

colorama.init()
print('\033[2J') # clear screen

give me error :
winterm.py line 111 in erase_data
coord_screen = win32.COORD(0,0)
AttributeError: 'module' has no attribute 'COORD'

python3.4 / windows7

colorama.init() breaks readline's history

Reported by email by 'Angel'

I am unable to use the history features of readline when using colorama.

I made a small Windows command line tool that uses python's raw_input to show a prompt to the user, which can then type a number of commands and execute them. I use the readline module and its read_history_file() and write_history_file() functions to make my tool remember the command history across sessions.

The problem is that if I don't use colorama the previous history loads fine and can be accessed by the user by using the up and down arrows, but as soon as I call the colorama.init() the history does not work anymore. In fact it seems to load a different history, which you can use, but as soon as you close the windows console that "colorama" history is lost.

I checked the functions exponsed by colorama and I found a couple of things that looked promising. I saw that you can call init(wrap=False) which seems that should restore the original stdin and stdout streams. There is also a deinit() function that seems to do the same. However, as soon as I try to use those I get the following traceback:

Readline internal error
Traceback (most recent call last):
  File "C:\Anaconda\lib\site-packages\pyreadline\console\console.py", line 768, in hook_wrapper_23
    res = ensure_str(readline_hook(prompt))
  File "C:\Anaconda\lib\site-packages\pyreadline\rlmain.py", line 569, in readline
    self.readline_setup(prompt)
  File "C:\Anaconda\lib\site-packages\pyreadline\rlmain.py", line 565, in readline_setup
    self._print_prompt()
  File "C:\Anaconda\lib\site-packages\pyreadline\rlmain.py", line 466, in _print_prompt
    x, y = c.pos()
  File "C:\Anaconda\lib\site-packages\pyreadline\console\console.py", line 261, in pos
    self.GetConsoleScreenBufferInfo(self.hout, byref(info))
ArgumentError: argument 2: <type 'exceptions.TypeError'>: expected LP_CONSOLE_SCREEN_BUFFER_INFO instance instead of pointer to CONSOLE_SCREEN_BUFFER_INFO
[9] <-
Readline internal error

So I cannot use this solution to fix my problem.

Is there something else that I could do? Maybe this is a Windows specific problem?

Any help would be appreciated. Thanks!

Migrated from https://code.google.com/p/colorama/issues/detail?id=57

Invalid unicode string handling

Migrated from https://code.google.com/p/colorama/issues/detail?id=21
Reported by av1024, Feb 23, 2011

What steps will reproduce the problem?

  1. import and initalize colorama with deafults
  2. print u"Some non-ASCII text ТЕСТ Русского"

What is the expected output?
Some non-ASCII text ТЕСТ Русского

What do you see instead?
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-5: ordinal not in range(128)

What version of the product are you using? On what operating system?
Python 2.7 (x32)
Windows 7 x64 Untimate (with Eng/Rus locales)

Please provide any additional information below.
Looks like wrapped write method hoes not inherit/use original stdout encoding. Possible fixes are (two ways):

A. use sys.setdefaultencoding(Your-Console-OEM-Encoding) # Wrong way IMHO. I don't know the simple method to determine right console mode (ANSI/OEM) and OEM encoding except reading 'stdout.encoding' property

B. Patch ansitowin32 to force-encode unicode output before .write:

--- D:\lg\py\colorama-0.1.18\colorama\ansitowin32.py    Tue May 18 14:43:54 2010
+++ ansitowin32.py  Wed Feb 23 19:10:40 2011
@@ -144,7 +144,10 @@

def write_plain_text(self, text, start, end):
    if start < end:
        self.wrapped.write(text[start:end])
        if isinstance(text, unicode):
            self.wrapped.write(text[start:end].encode(self.wrapped.encoding))
        else:
            self.wrapped.write(text[start:end])
        self.wrapped.flush()

Migrate issues list from google code to github

Would this be helpful? Then the google code repo can be deleted.

Presumably we'd need to triage the issues as they were migrated - I suspect many of them have been fixed in recent commits.

Crashes on 64 bit Windows (not tested on 32 bit Windows)

Trying to run following code on 64-bit Windows 7 (both x86 and x86_64 Pythons):

from colorama import init, ansi
init()
print(ansi.CSI + '2J')

The following happens:

Traceback (most recent call last):
  File "test.py", line 4, in <module>
    print(ansi.CSI + '2J')
  File "D:\Python3.x86\lib\site-packages\colorama\ansitowin32.py", line 35, in write
    self.__convertor.write(text)
  File "D:\Python3.x86\lib\site-packages\colorama\ansitowin32.py", line 117, in write
    self.write_and_convert(text)
  File "D:\Python3.x86\lib\site-packages\colorama\ansitowin32.py", line 142, in write_and_convert
    self.convert_ansi(*match.groups())
  File "D:\Python3.x86\lib\site-packages\colorama\ansitowin32.py", line 156, in convert_ansi
    self.call_win32(command, params)
  File "D:\Python3.x86\lib\site-packages\colorama\ansitowin32.py", line 183, in call_win32
    func(params, on_stderr=self.on_stderr)
  File "D:\Python3.x86\lib\site-packages\colorama\winterm.py", line 111, in erase_data
    coord_screen = win32.COORD(0,0)
AttributeError: 'module' object has no attribute 'COORD'

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.