Skip to content
Myr

Merge pull request #1784 from pallets/windows-requires-colorama

Before adoption: this commit came in with the history the project adopted, so no landing records it.

always install colorama on Windows

authored by David Lord · committed by GitHub · parents ea3bb6f, d7fac6e · Browse files · 15 files+83 added−120 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+83 added−120 removed

  • tests:+1 added−2 removed
  • other:+82 added−118 removed

15 files+83 added−120 removed

modified:docs/quickstart.rst+5 added-5 removed
106 unmodified lines
107* ``complex``: `Complex example with plugin loading108 <https://github.com/pallets/click/tree/master/examples/complex>`_109* ``validation``: `Custom parameter validation example110 <https://github.com/pallets/click/tree/master/examples/validation>`_111* ``colors``: `Colorama ANSI color support111* ``colors``: `Color support demo112 <https://github.com/pallets/click/tree/master/examples/colors>`_113* ``termui``: `Terminal UI functions demo114 <https://github.com/pallets/click/tree/master/examples/termui>`_115* ``imagepipe``: `Multi command chaining demo
49 unmodified lines
165What this means is that the :func:`echo` function applies some error166correction in case the terminal is misconfigured instead of dying with an167:exc:`UnicodeError`.168169As an added benefit, starting with Click 2.0, the echo function also170has good support for ANSI colors. It will automatically strip ANSI codes171if the output stream is a file and if colorama is supported, ANSI colors172will also work on Windows. See :ref:`ansi-colors`.169The echo function also supports color and other styles in output. It170will automatically remove styles if the output stream is a file. On171Windows, colorama is automatically installed and used. See172:ref:`ansi-colors`.173174If you don't need this, you can also use the `print()` construct /175function.176
123 unmodified lines
modified:docs/utils.rst+4 added-10 removed
50 unmodified lines
51-----------5253.. versionadded:: 2.05455The :func:`echo` function gained extra functionality to deal with ANSI56colors and styles. Note that on Windows, this functionality is only57available if `colorama`_ is installed. If it is installed, then ANSI58codes are intelligently handled.55The :func:`echo` function supports ANSI colors and styles. On Windows56this uses `colorama`_.5758Primarily this means that:5960- Click's :func:`echo` function will automatically strip ANSI color codes
2 unmodified lines
63 Windows and translate ANSI codes to terminal API calls. This means64 that colors will work on Windows the same way they do on other65 operating systems.6669Note for `colorama` support: Click will automatically detect when `colorama`70is available and use it. Do *not* call ``colorama.init()``!67On Windows, Click uses colorama without calling ``colorama.init()``. You68can still call that in your code, but it's not required for Click.6972To install `colorama`, run this command::7374 $ pip install colorama7570For styling a string, the :func:`style` function can be used::7172 import click73
330 unmodified lines
modified:examples/colors/colors.py+2 added-3 removed
21 unmodified lines
222324@click.command()25def cli():26 """This script prints some colors. If colorama is installed this will27 also work on Windows. It will also automatically remove all ANSI28 styles if data is piped into a file.26 """This script prints some colors. It will also automatically remove27 all ANSI styles if data is piped into a file.2829 Give it a try!30 """31 for color in all_colors:
8 unmodified lines
modified:examples/colors/README+1 added-1 removed
1 unmodified line
23 colors is a simple example that shows how you can4 colorize text.56 For this to work on Windows, colorama is required.6 Uses colorama on Windows.78Usage:910 $ pip install --editable .
1 unmodified line
modified:examples/colors/setup.py+1 added-5 removed
3 unmodified lines
4 name="click-example-colors",5 version="1.0",6 py_modules=["colors"],7 include_package_data=True,8 install_requires=[9 "click",10 # Colorama is only required for Windows.11 "colorama",12 ],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 colors=colors:cli12 """,
1 unmodified line
modified:examples/termui/setup.py+1 added-5 removed
3 unmodified lines
4 name="click-example-termui",5 version="1.0",6 py_modules=["termui"],7 include_package_data=True,8 install_requires=[9 "click",10 # Colorama is only required for Windows.11 "colorama",12 ],8 install_requires=["click"],9 entry_points="""10 [console_scripts]11 termui=termui:cli12 """,
1 unmodified line
modified:requirements/dev.txt-2 removed
18 unmodified lines
19chardet==4.0.020 # via requests21click==7.1.222 # via pip-tools23colorama==0.4.424 # via -r requirements/tests.in23distlib==0.3.124 # via virtualenv25docutils==0.1626 # via sphinx
112 unmodified lines
modified:requirements/tests.in-1 removed
1pytest2colorama2importlib_metadata
modified:requirements/tests.txt-2 removed
4 unmodified lines
5# pip-compile requirements/tests.in6#7attrs==20.3.08 # via pytest9colorama==0.4.410 # via -r requirements/tests.in9importlib-metadata==3.4.010 # via -r requirements/tests.in11iniconfig==1.1.112 # via pytest
14 unmodified lines
modified:src/click/_compat.py+35 added-39 removed
488 unmodified lines
489 return not isatty(stream) and not _is_jupyter_kernel_output(stream)490 return not color491492493# If we're on Windows, we provide transparent integration through494# colorama. This will make ANSI colors through the echo function495# work automatically.493# On Windows, wrap the output streams with colorama to support ANSI494# color codes.495# NOTE: double check is needed so mypy does not analyze this on Linux496if sys.platform.startswith("win") and WIN:497 from ._winconsole import _get_windows_console_stream498
1 unmodified line
500 import locale501502 return locale.getpreferredencoding()503504 _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()505506 def auto_wrap_for_ansi(507 stream: t.TextIO, color: t.Optional[bool] = None508 ) -> t.TextIO:509 """Support ANSI color and style codes on Windows by wrapping a510 stream with colorama.511 """505 try:512 try:513 cached = _ansi_stream_wrappers.get(stream)514 except Exception:515 cached = None516517 if cached is not None:518 return cached519520 import colorama507 except ImportError:508 pass509 else:510 _ansi_stream_wrappers: t.MutableMapping[511 t.TextIO, t.TextIO512 ] = WeakKeyDictionary()521514 def auto_wrap_for_ansi(515 stream: t.TextIO, color: t.Optional[bool] = None516 ) -> t.TextIO:517 """This function wraps a stream so that calls through colorama518 are issued to the win32 console API to recolor on demand. It519 also ensures to reset the colors if a write call is interrupted520 to not destroy the console afterwards.521 """522 strip = should_strip_ansi(stream, color)523 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)524 rv = ansi_wrapper.stream525 _write = rv.write526527 def _safe_write(s):528 try:523 cached = _ansi_stream_wrappers.get(stream)524 except Exception:525 cached = None526 if cached is not None:527 return cached528 strip = should_strip_ansi(stream, color)529 ansi_wrapper = colorama.AnsiToWin32(stream, strip=strip)530 rv = ansi_wrapper.stream531 _write = rv.write529 return _write(s)530 except BaseException:531 ansi_wrapper.reset_all()532 raise533533 def _safe_write(s):534 try:535 return _write(s)536 except BaseException:537 ansi_wrapper.reset_all()538 raise534 rv.write = _safe_write535540 rv.write = _safe_write541 try:542 _ansi_stream_wrappers[stream] = rv543 except Exception:544 pass536 try:537 _ansi_stream_wrappers[stream] = rv538 except Exception:539 pass545 return rv540541 return rv542543544else:545546 def _get_argv_encoding():547 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()
54 unmodified lines
modified:src/click/termui.py-3 removed
416 unmodified lines
417 .. versionadded:: 2.0418 """419 if not isatty(sys.stdout):420 return421 # If we're on Windows and we don't have colorama available, then we422 # clear the screen by shelling out. Otherwise we can use an escape423 # sequence.421 if WIN:422 os.system("cls")423 else:424 sys.stdout.write("\033[2J\033[1;1H")
297 unmodified lines
modified:src/click/utils.py+30 added-41 removed
170 unmodified lines
171 return iter(self._file)172173174def echo(message=None, file=None, nl=True, err=False, color=None):175 """Prints a message plus a newline to the given file or stdout. On176 first sight, this looks like the print function, but it has improved177 support for handling Unicode and binary data that does not fail no178 matter how badly configured the system is.175 """Print a message and newline to stdout or a file. This should be176 used instead of :func:`print` because it provides better support177 for different data, files, and environments.178180 Primarily it means that you can print binary data as well as Unicode181 data on both 2.x and 3.x to the given file in the most appropriate way182 possible. This is a very carefree function in that it will try its183 best to not fail. As of Click 6.0 this includes support for unicode184 output on the Windows console.179 Compared to :func:`print`, this does the following:180186 In addition to that, if `colorama`_ is installed, the echo function will187 also support clever handling of ANSI codes. Essentially it will then188 do the following:181 - Ensures that the output encoding is not misconfigured on Linux.182 - Supports Unicode in the Windows console.183 - Supports writing to binary outputs, and supports writing bytes184 to text outputs.185 - Supports colors and styles on Windows.186 - Removes ANSI color and style codes if the output does not look187 like an interactive terminal.188 - Always flushes the output.189190 - add transparent handling of ANSI color codes on Windows.191 - hide ANSI codes automatically if the destination file is not a192 terminal.190 :param message: The string or bytes to output. Other objects are191 converted to strings.192 :param file: The file to write to. Defaults to ``stdout``.193 :param err: Write to ``stderr`` instead of ``stdout``.194 :param nl: Print a newline after the message. Enabled by default.195 :param color: Force showing or hiding colors and other styles. By196 default Click will remove color if the output does not look like197 an interactive terminal.198194 .. _colorama: https://pypi.org/project/colorama/195199 .. versionchanged:: 6.0197 As of Click 6.0 the echo function will properly support unicode198 output on the windows console. Not that click does not modify199 the interpreter in any way which means that `sys.stdout` or the200 print statement or function will still not provide unicode support.200 Support Unicode output on the Windows console. Click does not201 modify ``sys.stdout``, so ``sys.stdout.write()`` and ``print()``202 will still not support Unicode.203202 .. versionchanged:: 2.0203 Starting with version 2.0 of Click, the echo function will work204 with colorama if it's installed.204 .. versionchanged:: 4.0205 Added the ``color`` parameter.206207 .. versionadded:: 3.0207 The `err` parameter was added.208 Added the ``err`` parameter.209209 .. versionchanged:: 4.0210 Added the `color` flag.211212 :param message: the message to print213 :param file: the file to write to (defaults to ``stdout``)214 :param err: if set to true the file defaults to ``stderr`` instead of215 ``stdout``. This is faster and easier than calling216 :func:`get_text_stderr` yourself.217 :param nl: if set to `True` (the default) a newline is printed afterwards.218 :param color: controls if the terminal supports ANSI colors or not. The219 default is autodetection.210 .. versionchanged:: 2.0211 Support colors on Windows if colorama is installed.212 """213 if file is None:214 if err:215 file = _default_text_stderr()
22 unmodified lines
238 binary_file.write(message)239 binary_file.flush()240 return241250 # ANSI-style support. If there is no message or we are dealing with251 # bytes nothing is happening. If we are connected to a file we want252 # to strip colors. If we are on windows we either wrap the stream253 # to strip the color or we use the colorama support to translate the254 # ansi codes to API calls.242 # ANSI style code support. For no message or bytes, nothing happens.243 # When outputting to a file instead of a terminal, strip codes.244 if message and not is_bytes(message):245 color = resolve_color_default(color)246 if should_strip_ansi(file, color):247 message = strip_ansi(message)
234 unmodified lines
modified:tests/test_imports.py+1 added-2 removed
39 unmodified lines
40 "inspect",41 "itertools",42 "io",43 "threading",44 "colorama",44 "errno",45 "fcntl",46 "datetime",47 "enum",
1 unmodified line
49 "types",50}5152if WIN:54 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])53 ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])545556def test_light_imports():57 c = subprocess.Popen(
10 unmodified lines
modified:CHANGES.rst+2 added
4 unmodified lines
56Unreleased78- Drop support for Python 2 and 3.5.9- Colorama is always installed on Windows in order to provide style10 and color support. :pr:`1784`11- Adds a repr to Command, showing the command name for friendlier12 debugging. :issue:`1267`, :pr:`1295`13- Add support for distinguishing the source of a command line14 parameter. :issue:`1264`, :pr:`1329`
795 unmodified lines
modified:setup.py+1 added-1 removed
1from setuptools import setup23setup(name="click")3setup(name="click", install_requires=["colorama; platform_system == 'Windows'"])