remove Python 2/3 from docs
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 9897d81 · Browse files · 10 files·+138 added−250 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+138 added−250 removed
- other:+138 added−250 removed
Provenance
- Commit
a1d726b- Tree
556f74b- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
9897d81
10 files changed+138 added−250 removed
modified:docs/index.rst+1 added-1 removed
79 unmodified lines80 testing81 utils82 bashcomplete83 exceptions84- python384+ unicode-support85 wincmd86 87 API Reference88 -------------19 unmodified linesdeleted:docs/python3.rst-191 removed
1-Python 3 Support2-================3-4-.. currentmodule:: click5-6-Click supports Python 3, but like all other command line utility libraries,7-it suffers from the Unicode text model in Python 3. All examples in the8-documentation were written so that they could run on both Python 2.x and9-Python 3.4 or higher.10-11-.. _python3-limitations:12-13-Python 3 Limitations14---------------------15-16-At the moment, Click suffers from a few problems with Python 3:17-18-* The command line in Unix traditionally is in bytes, not Unicode. While19- there are encoding hints for all of this, there are generally some20- situations where this can break. The most common one is SSH21- connections to machines with different locales.22-23- Misconfigured environments can currently cause a wide range of Unicode24- problems in Python 3 due to the lack of support for roundtripping25- surrogate escapes. This will not be fixed in Click itself!26-27- For more information see :ref:`python3-surrogates`.28-29-* Standard input and output in Python 3 is opened in Unicode mode by30- default. Click has to reopen the stream in binary mode in certain31- situations. Because there is no standardized way to do this, this32- might not always work. Primarily this can become a problem when33- testing command-line applications.34-35- This is not supported::36-37- sys.stdin = io.StringIO('Input here')38- sys.stdout = io.StringIO()39-40- Instead you need to do this::41-42- input = 'Input here'43- in_stream = io.BytesIO(input.encode('utf-8'))44- sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')45- out_stream = io.BytesIO()46- sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')47-48- Remember that in that case, you need to use ``out_stream.getvalue()``49- and not ``sys.stdout.getvalue()`` if you want to access the buffer50- contents as the wrapper will not forward that method.51-52-Python 2 and 3 Differences53---------------------------54-55-Click attempts to minimize the differences between Python 2 and Python 356-by following best practices for both languages.57-58-In Python 2, the following is true:59-60-* ``sys.stdin``, ``sys.stdout``, and ``sys.stderr`` are opened in binary61- mode, but under some circumstances they support Unicode output. Click62- attempts to not subvert this but provides support for forcing streams63- to be Unicode-based.64-* ``sys.argv`` is always byte-based. Click will pass bytes to all65- input types and convert as necessary. The :class:`STRING` type66- automatically will decode properly the input value into a string by67- trying the most appropriate encodings.68-* When dealing with files, Click will never go through the Unicode APIs69- and will instead use the operating system's byte APIs to open the70- files.71-72-In Python 3, the following is true:73-74-* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default75- text-based. When Click needs a binary stream, it attempts to discover76- the underlying binary stream. See :ref:`python3-limitations` for how77- this works.78-* ``sys.argv`` is always Unicode-based. This also means that the native79- type for input values to the types in Click is Unicode, and not bytes.80-81- This causes problems if the terminal is incorrectly set and Python82- does not figure out the encoding. In that case, the Unicode string83- will contain error bytes encoded as surrogate escapes.84-* When dealing with files, Click will always use the Unicode file system85- API calls by using the operating system's reported or guessed86- filesystem encoding. Surrogates are supported for filenames, so it87- should be possible to open files through the :class:`File` type even88- if the environment is misconfigured.89-90-.. _python3-surrogates:91-92-Python 3 Surrogate Handling93----------------------------94-95-Click in Python 3 does all the Unicode handling in the standard library96-and is subject to its behavior. In Python 2, Click does all the Unicode97-handling itself, which means there are differences in error behavior.98-99-The most glaring difference is that in Python 2, Unicode will "just work",100-while in Python 3, it requires extra care. The reason for this is that in101-Python 3, the encoding detection is done in the interpreter, and on Linux102-and certain other operating systems, its encoding handling is problematic.103-104-The biggest source of frustration is that Click scripts invoked by105-init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,106-puppet), or cron jobs (cron) will refuse to work unless a Unicode locale is107-exported.108-109-If Click encounters such an environment it will prevent further execution110-to force you to set a locale. This is done because Click cannot know111-about the state of the system once it's invoked and restore the values112-before Python's Unicode handling kicked in.113-114-If you see something like this error in Python 3::115-116- Traceback (most recent call last):117- ...118- RuntimeError: Click will abort further execution because Python 3 was119- configured to use ASCII as encoding for the environment. Either switch120- to Python 2 or consult the Python 3 section of the docs for121- mitigation steps.122-123-.. note::124-125- In Python 3.7 and later you will no longer get a ``RuntimeError`` in126- many cases thanks to :pep:`538` and :pep:`540`, which changed the127- default assumption in unconfigured environments.128-129-You are dealing with an environment where Python 3 thinks you are130-restricted to ASCII data. The solution to these problems is different131-depending on which locale your computer is running in.132-133-For instance, if you have a German Linux machine, you can fix the problem134-by exporting the locale to ``de_DE.utf-8``::135-136- export LC_ALL=de_DE.utf-8137- export LANG=de_DE.utf-8138-139-If you are on a US machine, ``en_US.utf-8`` is the encoding of choice. On140-some newer Linux systems, you could also try ``C.UTF-8`` as the locale::141-142- export LC_ALL=C.UTF-8143- export LANG=C.UTF-8144-145-On some systems it was reported that `UTF-8` has to be written as `UTF8`146-and vice versa. To see which locales are supported you can invoke147-``locale -a``::148-149- locale -a150-151-You need to do this before you invoke your Python script. If you are152-curious about the reasons for this, you can join the discussions in the153-Python 3 bug tracker:154-155-* `ASCII is a bad filesystem default encoding156- <https://bugs.python.org/issue13643#msg149941>`_157-* `Use surrogateescape as default error handler158- <https://bugs.python.org/issue19977>`_159-* `Python 3 raises Unicode errors in the C locale160- <https://bugs.python.org/issue19846>`_161-* `LC_CTYPE=C: pydoc leaves terminal in an unusable state162- <https://bugs.python.org/issue21398>`_ (this is relevant to Click163- because the pager support is provided by the stdlib pydoc module)164-165-Note (Python 3.7 onwards): Even though your locale may not be properly166-configured, Python 3.7 Click will not raise the above exception because Python167-3.7 programs are better at choosing default locales. This doesn't change the168-general issue that your locale may be misconfigured.169-170-Unicode Literals171-----------------172-173-Starting with Click 5.0 there will be a warning for the use of the174-``unicode_literals`` future import in Python 2. This has been done due to175-the negative consequences of this import with regards to unintentionally176-causing bugs due to introducing Unicode data to APIs that are incapable of177-handling them. For some examples of this issue, see the discussion on178-this github issue: `python-future#22179-<https://github.com/PythonCharmers/python-future/issues/22>`_.180-181-If you use ``unicode_literals`` in any file that defines a Click command182-or that invokes a click command you will be given a warning. You are183-strongly encouraged to not use ``unicode_literals`` and instead use184-explicit ``u`` prefixes for your Unicode strings.185-186-If you do want to ignore the warning and continue using187-``unicode_literals`` on your own peril, you can disable the warning as188-follows::189-190- import click191- click.disable_unicode_literals_warning = Truemodified:docs/quickstart.rst+2 added-4 removed
155 unmodified lines156 -------157 158 Why does this example use :func:`echo` instead of the regular159 :func:`print` function? The answer to this question is that Click160-attempts to support both Python 2 and Python 3 the same way and to be very160+attempts to support different environments consistently and to be very161 robust even when the environment is misconfigured. Click wants to be162 functional at least on a basic level even if everything is completely163 broken.164 3 unmodified lines168 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. Note that in Python 2, the :func:`echo` function173-does not parse color code information from bytearrays. See :ref:`ansi-colors`174-for more information.172+will also work on Windows. See :ref:`ansi-colors`.173 174 If you don't need this, you can also use the `print()` construct /175 function.176 99 unmodified linesadded:docs/unicode-support.rst+112 added
1+Unicode Support2+===============3+4+.. currentmodule:: click5+6+Click has to take extra care to support Unicode text in different7+environments.8+9+* The command line in Unix is traditionally bytes, not Unicode. While10+ there are encoding hints, there are some situations where this can11+ break. The most common one is SSH connections to machines with12+ different locales.13+14+ Misconfigured environments can cause a wide range of Unicode15+ problems due to the lack of support for roundtripping surrogate16+ escapes. This will not be fixed in Click itself!17+18+* Standard input and output is opened in text mode by default. Click19+ has to reopen the stream in binary mode in certain situations.20+ Because there is no standard way to do this, it might not always21+ work. Primarily this can become a problem when testing command-line22+ applications.23+24+ This is not supported::25+26+ sys.stdin = io.StringIO('Input here')27+ sys.stdout = io.StringIO()28+29+ Instead you need to do this::30+31+ input = 'Input here'32+ in_stream = io.BytesIO(input.encode('utf-8'))33+ sys.stdin = io.TextIOWrapper(in_stream, encoding='utf-8')34+ out_stream = io.BytesIO()35+ sys.stdout = io.TextIOWrapper(out_stream, encoding='utf-8')36+37+ Remember in that case, you need to use ``out_stream.getvalue()``38+ and not ``sys.stdout.getvalue()`` if you want to access the buffer39+ contents as the wrapper will not forward that method.40+41+* ``sys.stdin``, ``sys.stdout`` and ``sys.stderr`` are by default42+ text-based. When Click needs a binary stream, it attempts to43+ discover the underlying binary stream.44+45+* ``sys.argv`` is always text. This means that the native type for46+ input values to the types in Click is Unicode, not bytes.47+48+ This causes problems if the terminal is incorrectly set and Python49+ does not figure out the encoding. In that case, the Unicode string50+ will contain error bytes encoded as surrogate escapes.51+52+* When dealing with files, Click will always use the Unicode file53+ system API by using the operating system's reported or guessed54+ filesystem encoding. Surrogates are supported for filenames, so it55+ should be possible to open files through the :class:`File` type even56+ if the environment is misconfigured.57+58+59+Surrogate Handling60+------------------61+62+Click does all the Unicode handling in the standard library and is63+subject to its behavior. Unicode requires extra care. The reason for64+this is that the encoding detection is done in the interpreter, and on65+Linux and certain other operating systems, its encoding handling is66+problematic.67+68+The biggest source of frustration is that Click scripts invoked by init69+systems, deployment tools, or cron jobs will refuse to work unless a70+Unicode locale is exported.71+72+If Click encounters such an environment it will prevent further73+execution to force you to set a locale. This is done because Click74+cannot know about the state of the system once it's invoked and restore75+the values before Python's Unicode handling kicked in.76+77+If you see something like this error::78+79+ Traceback (most recent call last):80+ ...81+ RuntimeError: Click will abort further execution because Python was82+ configured to use ASCII as encoding for the environment. Consult83+ https://click.palletsprojects.com/unicode-support/ for mitigation84+ steps.85+86+You are dealing with an environment where Python thinks you are87+restricted to ASCII data. The solution to these problems is different88+depending on which locale your computer is running in.89+90+For instance, if you have a German Linux machine, you can fix the91+problem by exporting the locale to ``de_DE.utf-8``::92+93+ export LC_ALL=de_DE.utf-894+ export LANG=de_DE.utf-895+96+If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97+On some newer Linux systems, you could also try ``C.UTF-8`` as the98+locale::99+100+ export LC_ALL=C.UTF-8101+ export LANG=C.UTF-8102+103+On some systems it was reported that ``UTF-8`` has to be written as104+``UTF8`` and vice versa. To see which locales are supported you can105+invoke ``locale -a``.106+107+You need to export the values before you invoke your Python script.108+109+In Python 3.7 and later you will no longer get a ``RuntimeError`` in110+many cases thanks to :pep:`538` and :pep:`540`, which changed the111+default assumption in unconfigured environments. This doesn't change the112+general issue that your locale may be misconfigured.modified:docs/utils.rst+12 added-22 removed
11 unmodified lines12 ------------------13 14 The most obvious helper is the :func:`echo` function, which in many ways15 works like the Python ``print`` statement or function. The main difference is16-that it works the same in Python 2 and 3, it intelligently detects17-misconfigured output streams, and it will never fail (except in Python 3; for18-more information see :ref:`python3-limitations`).16+that it works the same in many different terminal environments.17 18 Example::19 20 import click21 22 click.echo('Hello World!')23 26-Most importantly, it can print both Unicode and binary data, unlike the27-built-in ``print`` function in Python 3, which cannot output any bytes. It28-will, however, emit a trailing newline by default, which needs to be29-suppressed by passing ``nl=False``::24+It can output both text and binary data. It will emit a trailing newline25+by default, which needs to be suppressed by passing ``nl=False``::26 27 click.echo(b'\xe2\x98\x83', nl=False)28 29 Last but not least :func:`echo` uses click's intelligent internal output30 streams to stdout and stderr which support unicode output on the Windows31 console. This means for as long as you are using `click.echo` you can32 output unicode characters (there are some limitations on the default font37-with regards to which characters can be displayed). This functionality is38-new in Click 6.0.33+with regards to which characters can be displayed).34 35 .. versionadded:: 6.036 42-Click now emulates output streams on Windows to support unicode to the37+Click emulates output streams on Windows to support unicode to the38 Windows console through separate APIs. For more information see39 :doc:`wincmd`.40 41 .. versionadded:: 3.042 48-Starting with Click 3.0 you can also easily print to standard error by49-passing ``err=True``::43+You can also easily print to standard error by passing ``err=True``::44 45 click.echo('Hello World!', err=True)46 47 3 unmodified lines51 -----------52 53 .. versionadded:: 2.054 61-Starting with Click 2.0, the :func:`echo` function gained extra62-functionality to deal with ANSI colors and styles. Note that on Windows,63-this functionality is only available if `colorama`_ is installed. If it64-is installed, then ANSI codes are intelligently handled. Note that in Python65-2, the echo function doesn't parse color code information from bytearrays.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.59 60 Primarily this means that:61 62 - Click's :func:`echo` function will automatically strip ANSI color codes181 unmodified lines244 Printing Filenames245 ------------------246 247 Because filenames might not be Unicode, formatting them can be a bit255-tricky. Generally, this is easier in Python 2 than on 3, as you can just256-write the bytes to stdout with the ``print`` function, but in Python 3, you257-will always need to operate in Unicode.248+tricky.249 250 The way this works with click is through the :func:`format_filename`251 function. It does a best-effort conversion of the filename to Unicode and252 will never fail. This makes it possible to use these filenames in the17 unmodified lines270 :func:`get_text_stream` functions, which produce consistent results with271 different Python versions and for a wide variety of terminal configurations.272 273 The end result is that these functions will always return a functional283-stream object (except in very odd cases in Python 3; see284-:ref:`python3-limitations`).274+stream object (except in very odd cases; see :doc:`/unicode-support`).275 276 Example::277 278 import click131 unmodified linesmodified:docs/why.rst-1 removed
10 unmodified lines11 * supports implementation of Unix/POSIX command line conventions12 * supports loading values from environment variables out of the box13 * support for prompting of custom values14 * is fully nestable and composable15-* works the same in Python 2 and 315 * supports file handling out of the box16 * comes with useful common helpers (getting terminal dimensions,17 ANSI colors, fetching direct keyboard input, screen clearing,18 finding config paths, launching apps and editors, etc.)128 unmodified linesmodified:docs/wincmd.rst+1 added-17 removed
1 unmodified line2 =====================3 4 .. versionadded:: 6.05 6-Until Click 6.0 there are various bugs and limitations with using Click on7-a Windows console. Most notably the decoding of command line arguments8-was performed with the wrong encoding on Python 2 and on all versions of9-Python output of unicode characters was impossible. Starting with Click10-6.0 we now emulate output streams on Windows to support unicode to the6+Click emulates output streams on Windows to support unicode to the7 Windows console through separate APIs and we perform different decoding of8 parameters.9 10 Here is a brief overview of how this works and what it means to you.6 unmodified lines17 performed to the type expected value as late as possible. This has some18 advantages as it allows us to accept the data in the most appropriate form19 for the operating system and Python version.20 25-For instance paths are left as bytes on Python 2 unless you explicitly26-tell it otherwise.27-21 This caused some problems on Windows where initially the wrong encoding22 was used and garbage ended up in your input data. We not only fixed the23 encoding part, but we also now extract unicode parameters from `sys.argv`.24 32-This means that on Python 2 under Windows, the arguments processed will33-*most likely* be of unicode nature and not bytes. This was something that34-previously did not really happen unless you explicitly passed in unicode35-parameters so your custom types need to be aware of this.36-25 There is also another limitation with this: if `sys.argv` was modified26 prior to invoking a click handler, we have to fall back to the regular27 byte input in which case not all unicode values are available but only a28 subset of the codepage used for parameters.13 unmodified lines42 stream will also use ``utf-16-le`` as internal encoding. However there is43 some hackery going on that the underlying raw IO buffer is still bypassing44 the unicode APIs and byte output through an indirection is still possible.45 58-This hackery is used on both Python 2 and Python 3 as neither version of59-Python has native support for cmd.exe with unicode characters. There are60-some limitations you need to be aware of:61-46 * This unicode support is limited to ``click.echo``, ``click.prompt`` as47 well as ``click.get_text_stream``.48 * Depending on if unicode values or byte strings are passed the control49 flow goes completely different places internally which can have some15 unmodified linesmodified:src/click/_unicodefun.py+5 added-5 removed
1 import codecs2 import os3 4 5-def _verify_python3_env():6- """Ensures that the environment is good for unicode on Python 3."""5+def _verify_python_env():6+ """Ensures that the environment is good for Unicode."""7 try:8 import locale9 10 fs_enc = codecs.lookup(locale.getpreferredencoding()).name63 unmodified lines74 f" {bad_locale!r} but it is not supported"75 )76 77 raise RuntimeError(78- "Click will abort further execution because Python 3 was"78+ "Click will abort further execution because Python was"79 " configured to use ASCII as encoding for the environment."80- " Consult https://click.palletsprojects.com/python3/ for"81- f" mitigation steps.{extra}"80+ " Consult https://click.palletsprojects.com/unicode-support/"81+ f" for mitigation steps.{extra}"82 )modified:src/click/core.py+2 added-2 removed
4 unmodified lines5 from contextlib import contextmanager6 from functools import update_wrapper7 from itertools import repeat8 9-from ._unicodefun import _verify_python3_env9+from ._unicodefun import _verify_python_env10 from .exceptions import Abort11 from .exceptions import BadParameter12 from .exceptions import ClickException13 from .exceptions import Exit772 unmodified lines786 constructor. See :class:`Context` for more information.787 """788 # Verify that the environment is configured correctly, or reject789 # further execution to avoid a broken script.790- _verify_python3_env()790+ _verify_python_env()791 792 if args is None:793 args = sys.argv[1:]794 else:1276 unmodified linesmodified:src/click/utils.py+3 added-7 removed
263 unmodified lines264 file.flush()265 266 267 def get_binary_stream(name):268- """Returns a system stream for byte processing. This essentially269- returns the stream from the sys module with the given name but it270- solves some compatibility issues between different Python versions.271- Primarily this function is necessary for getting binary streams on272- Python 3.268+ """Returns a system stream for byte processing.269 270 :param name: the name of the stream to open. Valid names are ``'stdin'``,271 ``'stdout'`` and ``'stderr'``272 """5 unmodified lines278 279 def get_text_stream(name, encoding=None, errors="strict"):280 """Returns a system stream for text processing. This usually returns281 a wrapped stream around a binary stream returned from286- :func:`get_binary_stream` but it also can take shortcuts on Python 3287- for already correctly configured streams.282+ :func:`get_binary_stream` but it also can take shortcuts for already283+ correctly configured streams.284 285 :param name: the name of the stream to open. Valid names are ``'stdin'``,286 ``'stdout'`` and ``'stderr'``287 :param encoding: overrides the detected default encoding.153 unmodified lines