Skip to content
Myr

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

10 files+138 added−250 removed

modified:docs/index.rst+1 added-1 removed
79 unmodified lines
80 testing81 utils82 bashcomplete83 exceptions84 python384 unicode-support85 wincmd8687API Reference88-------------
19 unmodified lines
deleted:docs/python3.rst-191 removed
1Python 3 Support2================34.. currentmodule:: click56Click supports Python 3, but like all other command line utility libraries,7it suffers from the Unicode text model in Python 3. All examples in the8documentation were written so that they could run on both Python 2.x and9Python 3.4 or higher.1011.. _python3-limitations:1213Python 3 Limitations14--------------------1516At the moment, Click suffers from a few problems with Python 3:1718* 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.2223 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!2627 For more information see :ref:`python3-surrogates`.2829* 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.3435 This is not supported::3637 sys.stdin = io.StringIO('Input here')38 sys.stdout = io.StringIO()3940 Instead you need to do this::4142 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')4748 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.5152Python 2 and 3 Differences53--------------------------5455Click attempts to minimize the differences between Python 2 and Python 356by following best practices for both languages.5758In Python 2, the following is true:5960* ``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.7172In Python 3, the following is true:7374* ``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.8081 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.8990.. _python3-surrogates:9192Python 3 Surrogate Handling93---------------------------9495Click in Python 3 does all the Unicode handling in the standard library96and is subject to its behavior. In Python 2, Click does all the Unicode97handling itself, which means there are differences in error behavior.9899The most glaring difference is that in Python 2, Unicode will "just work",100while in Python 3, it requires extra care. The reason for this is that in101Python 3, the encoding detection is done in the interpreter, and on Linux102and certain other operating systems, its encoding handling is problematic.103104The biggest source of frustration is that Click scripts invoked by105init systems (sysvinit, upstart, systemd, etc.), deployment tools (salt,106puppet), or cron jobs (cron) will refuse to work unless a Unicode locale is107exported.108109If Click encounters such an environment it will prevent further execution110to force you to set a locale. This is done because Click cannot know111about the state of the system once it's invoked and restore the values112before Python's Unicode handling kicked in.113114If you see something like this error in Python 3::115116 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.122123.. note::124125 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.128129You are dealing with an environment where Python 3 thinks you are130restricted to ASCII data. The solution to these problems is different131depending on which locale your computer is running in.132133For instance, if you have a German Linux machine, you can fix the problem134by exporting the locale to ``de_DE.utf-8``::135136 export LC_ALL=de_DE.utf-8137 export LANG=de_DE.utf-8138139If you are on a US machine, ``en_US.utf-8`` is the encoding of choice. On140some newer Linux systems, you could also try ``C.UTF-8`` as the locale::141142 export LC_ALL=C.UTF-8143 export LANG=C.UTF-8144145On some systems it was reported that `UTF-8` has to be written as `UTF8`146and vice versa. To see which locales are supported you can invoke147``locale -a``::148149 locale -a150151You need to do this before you invoke your Python script. If you are152curious about the reasons for this, you can join the discussions in the153Python 3 bug tracker:154155* `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)164165Note (Python 3.7 onwards): Even though your locale may not be properly166configured, Python 3.7 Click will not raise the above exception because Python1673.7 programs are better at choosing default locales. This doesn't change the168general issue that your locale may be misconfigured.169170Unicode Literals171----------------172173Starting 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 to175the negative consequences of this import with regards to unintentionally176causing bugs due to introducing Unicode data to APIs that are incapable of177handling them. For some examples of this issue, see the discussion on178this github issue: `python-future#22179<https://github.com/PythonCharmers/python-future/issues/22>`_.180181If you use ``unicode_literals`` in any file that defines a Click command182or that invokes a click command you will be given a warning. You are183strongly encouraged to not use ``unicode_literals`` and instead use184explicit ``u`` prefixes for your Unicode strings.185186If you do want to ignore the warning and continue using187``unicode_literals`` on your own peril, you can disable the warning as188follows::189190 import click191 click.disable_unicode_literals_warning = True
modified:docs/quickstart.rst+2 added-4 removed
155 unmodified lines
156-------157158Why does this example use :func:`echo` instead of the regular159:func:`print` function? The answer to this question is that Click160attempts to support both Python 2 and Python 3 the same way and to be very160attempts to support different environments consistently and to be very161robust even when the environment is misconfigured. Click wants to be162functional at least on a basic level even if everything is completely163broken.164
3 unmodified lines
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. Note that in Python 2, the :func:`echo` function173does not parse color code information from bytearrays. See :ref:`ansi-colors`174for more information.172will also work on Windows. See :ref:`ansi-colors`.173174If you don't need this, you can also use the `print()` construct /175function.176
99 unmodified lines
added:docs/unicode-support.rst+112 added
1Unicode Support2===============34.. currentmodule:: click56Click has to take extra care to support Unicode text in different7environments.89* 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.1314 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!1718* 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.2324 This is not supported::2526 sys.stdin = io.StringIO('Input here')27 sys.stdout = io.StringIO()2829 Instead you need to do this::3031 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')3637 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.4041* ``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.4445* ``sys.argv`` is always text. This means that the native type for46 input values to the types in Click is Unicode, not bytes.4748 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.5152* 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.575859Surrogate Handling60------------------6162Click does all the Unicode handling in the standard library and is63subject to its behavior. Unicode requires extra care. The reason for64this is that the encoding detection is done in the interpreter, and on65Linux and certain other operating systems, its encoding handling is66problematic.6768The biggest source of frustration is that Click scripts invoked by init69systems, deployment tools, or cron jobs will refuse to work unless a70Unicode locale is exported.7172If Click encounters such an environment it will prevent further73execution to force you to set a locale. This is done because Click74cannot know about the state of the system once it's invoked and restore75the values before Python's Unicode handling kicked in.7677If you see something like this error::7879 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.8586You are dealing with an environment where Python thinks you are87restricted to ASCII data. The solution to these problems is different88depending on which locale your computer is running in.8990For instance, if you have a German Linux machine, you can fix the91problem by exporting the locale to ``de_DE.utf-8``::9293 export LC_ALL=de_DE.utf-894 export LANG=de_DE.utf-89596If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.97On some newer Linux systems, you could also try ``C.UTF-8`` as the98locale::99100 export LC_ALL=C.UTF-8101 export LANG=C.UTF-8102103On some systems it was reported that ``UTF-8`` has to be written as104``UTF8`` and vice versa. To see which locales are supported you can105invoke ``locale -a``.106107You need to export the values before you invoke your Python script.108109In Python 3.7 and later you will no longer get a ``RuntimeError`` in110many cases thanks to :pep:`538` and :pep:`540`, which changed the111default assumption in unconfigured environments. This doesn't change the112general issue that your locale may be misconfigured.
modified:docs/utils.rst+12 added-22 removed
11 unmodified lines
12------------------1314The most obvious helper is the :func:`echo` function, which in many ways15works like the Python ``print`` statement or function. The main difference is16that it works the same in Python 2 and 3, it intelligently detects17misconfigured output streams, and it will never fail (except in Python 3; for18more information see :ref:`python3-limitations`).16that it works the same in many different terminal environments.1718Example::1920 import click2122 click.echo('Hello World!')2326Most importantly, it can print both Unicode and binary data, unlike the27built-in ``print`` function in Python 3, which cannot output any bytes. It28will, however, emit a trailing newline by default, which needs to be29suppressed by passing ``nl=False``::24It can output both text and binary data. It will emit a trailing newline25by default, which needs to be suppressed by passing ``nl=False``::2627 click.echo(b'\xe2\x98\x83', nl=False)2829Last but not least :func:`echo` uses click's intelligent internal output30streams to stdout and stderr which support unicode output on the Windows31console. This means for as long as you are using `click.echo` you can32output unicode characters (there are some limitations on the default font37with regards to which characters can be displayed). This functionality is38new in Click 6.0.33with regards to which characters can be displayed).3435.. versionadded:: 6.03642Click now emulates output streams on Windows to support unicode to the37Click emulates output streams on Windows to support unicode to the38Windows console through separate APIs. For more information see39:doc:`wincmd`.4041.. versionadded:: 3.04248Starting with Click 3.0 you can also easily print to standard error by49passing ``err=True``::43You can also easily print to standard error by passing ``err=True``::4445 click.echo('Hello World!', err=True)4647
3 unmodified lines
51-----------5253.. versionadded:: 2.05461Starting with Click 2.0, the :func:`echo` function gained extra62functionality to deal with ANSI colors and styles. Note that on Windows,63this functionality is only available if `colorama`_ is installed. If it64is installed, then ANSI codes are intelligently handled. Note that in Python652, the echo function doesn't parse color code information from bytearrays.55The :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.5960Primarily this means that:6162- Click's :func:`echo` function will automatically strip ANSI color codes
181 unmodified lines
244Printing Filenames245------------------246247Because filenames might not be Unicode, formatting them can be a bit255tricky. Generally, this is easier in Python 2 than on 3, as you can just256write the bytes to stdout with the ``print`` function, but in Python 3, you257will always need to operate in Unicode.248tricky.249250The way this works with click is through the :func:`format_filename`251function. It does a best-effort conversion of the filename to Unicode and252will never fail. This makes it possible to use these filenames in the
17 unmodified lines
270:func:`get_text_stream` functions, which produce consistent results with271different Python versions and for a wide variety of terminal configurations.272273The end result is that these functions will always return a functional283stream object (except in very odd cases in Python 3; see284:ref:`python3-limitations`).274stream object (except in very odd cases; see :doc:`/unicode-support`).275276Example::277278 import click
131 unmodified lines
modified:docs/why.rst-1 removed
10 unmodified lines
11* 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 lines
modified:docs/wincmd.rst+1 added-17 removed
1 unmodified line
2=====================34.. versionadded:: 6.056Until Click 6.0 there are various bugs and limitations with using Click on7a Windows console. Most notably the decoding of command line arguments8was performed with the wrong encoding on Python 2 and on all versions of9Python output of unicode characters was impossible. Starting with Click106.0 we now emulate output streams on Windows to support unicode to the6Click emulates output streams on Windows to support unicode to the7Windows console through separate APIs and we perform different decoding of8parameters.910Here is a brief overview of how this works and what it means to you.
6 unmodified lines
17performed to the type expected value as late as possible. This has some18advantages as it allows us to accept the data in the most appropriate form19for the operating system and Python version.2025For instance paths are left as bytes on Python 2 unless you explicitly26tell it otherwise.2721This caused some problems on Windows where initially the wrong encoding22was used and garbage ended up in your input data. We not only fixed the23encoding part, but we also now extract unicode parameters from `sys.argv`.2432This means that on Python 2 under Windows, the arguments processed will33*most likely* be of unicode nature and not bytes. This was something that34previously did not really happen unless you explicitly passed in unicode35parameters so your custom types need to be aware of this.3625There is also another limitation with this: if `sys.argv` was modified26prior to invoking a click handler, we have to fall back to the regular27byte input in which case not all unicode values are available but only a28subset of the codepage used for parameters.
13 unmodified lines
42stream will also use ``utf-16-le`` as internal encoding. However there is43some hackery going on that the underlying raw IO buffer is still bypassing44the unicode APIs and byte output through an indirection is still possible.4558This hackery is used on both Python 2 and Python 3 as neither version of59Python has native support for cmd.exe with unicode characters. There are60some limitations you need to be aware of:6146* 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 some
15 unmodified lines
modified:src/click/_unicodefun.py+5 added-5 removed
1import codecs2import os345def _verify_python3_env():6 """Ensures that the environment is good for unicode on Python 3."""5def _verify_python_env():6 """Ensures that the environment is good for Unicode."""7 try:8 import locale910 fs_enc = codecs.lookup(locale.getpreferredencoding()).name
63 unmodified lines
74 f" {bad_locale!r} but it is not supported"75 )7677 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 lines
5from contextlib import contextmanager6from functools import update_wrapper7from itertools import repeat89from ._unicodefun import _verify_python3_env9from ._unicodefun import _verify_python_env10from .exceptions import Abort11from .exceptions import BadParameter12from .exceptions import ClickException13from .exceptions import Exit
772 unmodified lines
786 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()791792 if args is None:793 args = sys.argv[1:]794 else:
1276 unmodified lines
modified:src/click/utils.py+3 added-7 removed
263 unmodified lines
264 file.flush()265266267def 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.269270 :param name: the name of the stream to open. Valid names are ``'stdin'``,271 ``'stdout'`` and ``'stderr'``272 """
5 unmodified lines
278279def 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.284285 :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