always install colorama on Windows
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent ea3bb6f · 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
Provenance
- Commit
d7fac6e- Tree
841cd96- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
ea3bb6f
15 files changed+83 added−120 removed
modified:docs/quickstart.rst+5 added-5 removed
106 unmodified lines107 * ``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 demo49 unmodified lines165 What this means is that the :func:`echo` function applies some error166 correction in case the terminal is misconfigured instead of dying with an167 :exc:`UnicodeError`.168 169-As an added benefit, starting with Click 2.0, the echo function also170-has good support for ANSI colors. It will automatically strip ANSI codes171-if the output stream is a file and if colorama is supported, ANSI colors172-will also work on Windows. See :ref:`ansi-colors`.169+The echo function also supports color and other styles in output. It170+will automatically remove styles if the output stream is a file. On171+Windows, colorama is automatically installed and used. See172+:ref:`ansi-colors`.173 174 If you don't need this, you can also use the `print()` construct /175 function.176 123 unmodified linesmodified:docs/utils.rst+4 added-10 removed
50 unmodified lines51 -----------52 53 .. versionadded:: 2.054 55-The :func:`echo` function gained extra functionality to deal with ANSI56-colors and styles. Note that on Windows, this functionality is only57-available if `colorama`_ is installed. If it is installed, then ANSI58-codes are intelligently handled.55+The :func:`echo` function supports ANSI colors and styles. On Windows56+this uses `colorama`_.57 58 Primarily this means that:59 60 - Click's :func:`echo` function will automatically strip ANSI color codes2 unmodified lines63 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.66 69-Note for `colorama` support: Click will automatically detect when `colorama`70-is available and use it. Do *not* call ``colorama.init()``!67+On Windows, Click uses colorama without calling ``colorama.init()``. You68+can still call that in your code, but it's not required for Click.69 72-To install `colorama`, run this command::73-74- $ pip install colorama75-70 For styling a string, the :func:`style` function can be used::71 72 import click73 330 unmodified linesmodified:examples/colors/colors.py+2 added-3 removed
21 unmodified lines22 23 24 @click.command()25 def 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.28 29 Give it a try!30 """31 for color in all_colors:8 unmodified linesmodified:examples/colors/README+1 added-1 removed
1 unmodified line2 3 colors is a simple example that shows how you can4 colorize text.5 6- For this to work on Windows, colorama is required.6+ Uses colorama on Windows.7 8 Usage:9 10 $ pip install --editable .1 unmodified linemodified:examples/colors/setup.py+1 added-5 removed
3 unmodified lines4 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 linemodified:examples/termui/setup.py+1 added-5 removed
3 unmodified lines4 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 linemodified:requirements/dev.txt-2 removed
18 unmodified lines19 chardet==4.0.020 # via requests21 click==7.1.222 # via pip-tools23-colorama==0.4.424- # via -r requirements/tests.in23 distlib==0.3.124 # via virtualenv25 docutils==0.1626 # via sphinx112 unmodified linesmodified:requirements/tests.in-1 removed
1 pytest2-colorama2 importlib_metadatamodified:requirements/tests.txt-2 removed
4 unmodified lines5 # pip-compile requirements/tests.in6 #7 attrs==20.3.08 # via pytest9-colorama==0.4.410- # via -r requirements/tests.in9 importlib-metadata==3.4.010 # via -r requirements/tests.in11 iniconfig==1.1.112 # via pytest14 unmodified linesmodified:src/click/_compat.py+35 added-39 removed
488 unmodified lines489 return not isatty(stream) and not _is_jupyter_kernel_output(stream)490 return not color491 492 493-# 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 Linux496 if sys.platform.startswith("win") and WIN:497 from ._winconsole import _get_windows_console_stream498 1 unmodified line500 import locale501 502 return locale.getpreferredencoding()503 504+ _ansi_stream_wrappers: t.MutableMapping[t.TextIO, t.TextIO] = WeakKeyDictionary()505+506+ 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 = None516+517+ if cached is not None:518+ return cached519+520 import colorama507- except ImportError:508- pass509- else:510- _ansi_stream_wrappers: t.MutableMapping[511- t.TextIO, t.TextIO512- ] = WeakKeyDictionary()521 514- 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.write526+527+ 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+ raise533 533- def _safe_write(s):534- try:535- return _write(s)536- except BaseException:537- ansi_wrapper.reset_all()538- raise534+ rv.write = _safe_write535 540- 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 rv540 541+ return rv542 543+544 else:545 546 def _get_argv_encoding():547 return getattr(sys.stdin, "encoding", None) or get_filesystem_encoding()54 unmodified linesmodified:src/click/termui.py-3 removed
416 unmodified lines417 .. 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 linesmodified:src/click/utils.py+30 added-41 removed
170 unmodified lines171 return iter(self._file)172 173 174 def 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.178 180- 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:180 186- 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.189 190- - 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.198 194- .. _colorama: https://pypi.org/project/colorama/195-199 .. 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.203 202- .. 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.206 207 .. versionadded:: 3.0207- The `err` parameter was added.208+ Added the ``err`` parameter.209 209- .. versionchanged:: 4.0210- Added the `color` flag.211-212- :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 lines238 binary_file.write(message)239 binary_file.flush()240 return241 250- # 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 linesmodified:tests/test_imports.py+1 added-2 removed
39 unmodified lines40 "inspect",41 "itertools",42 "io",43 "threading",44- "colorama",44 "errno",45 "fcntl",46 "datetime",47 "enum",1 unmodified line49 "types",50 }51 52 if WIN:54- ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time", "zlib"])53+ ALLOWED_IMPORTS.update(["ctypes", "ctypes.wintypes", "msvcrt", "time"])54 55 56 def test_light_imports():57 c = subprocess.Popen(10 unmodified linesmodified:CHANGES.rst+2 added
4 unmodified lines5 6 Unreleased7 8 - 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 linesmodified:setup.py+1 added-1 removed
1 from setuptools import setup2 3-setup(name="click")3+setup(name="click", install_requires=["colorama; platform_system == 'Windows'"])