Skip to content
Myr

python3.rst

This file

Path

docs/python3.rst

185 lines · 7.6 KiB

Last changed by

Merge branch '7.x'David Lordbefore adoption11abf2b

History of this file

Take it

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.122123You are dealing with an environment where Python 3 thinks you are124restricted to ASCII data.  The solution to these problems is different125depending on which locale your computer is running in.126127For instance, if you have a German Linux machine, you can fix the problem128by exporting the locale to ``de_DE.utf-8``::129130    export LC_ALL=de_DE.utf-8131    export LANG=de_DE.utf-8132133If you are on a US machine, ``en_US.utf-8`` is the encoding of choice.  On134some newer Linux systems, you could also try ``C.UTF-8`` as the locale::135136    export LC_ALL=C.UTF-8137    export LANG=C.UTF-8138139On some systems it was reported that `UTF-8` has to be written as `UTF8`140and vice versa.  To see which locales are supported you can invoke141``locale -a``::142143    locale -a144145You need to do this before you invoke your Python script.  If you are146curious about the reasons for this, you can join the discussions in the147Python 3 bug tracker:148149*   `ASCII is a bad filesystem default encoding150    <https://bugs.python.org/issue13643#msg149941>`_151*   `Use surrogateescape as default error handler152    <https://bugs.python.org/issue19977>`_153*   `Python 3 raises Unicode errors in the C locale154    <https://bugs.python.org/issue19846>`_155*   `LC_CTYPE=C:  pydoc leaves terminal in an unusable state156    <https://bugs.python.org/issue21398>`_ (this is relevant to Click157    because the pager support is provided by the stdlib pydoc module)158159Note (Python 3.7 onwards): Even though your locale may not be properly160configured, Python 3.7 Click will not raise the above exception because Python1613.7 programs are better at choosing default locales.  This doesn't change the162general issue that your locale may be misconfigured.163164Unicode Literals165----------------166167Starting with Click 5.0 there will be a warning for the use of the168``unicode_literals`` future import in Python 2.  This has been done due to169the negative consequences of this import with regards to unintentionally170causing bugs due to introducing Unicode data to APIs that are incapable of171handling them.  For some examples of this issue, see the discussion on172this github issue: `python-future#22173<https://github.com/PythonCharmers/python-future/issues/22>`_.174175If you use ``unicode_literals`` in any file that defines a Click command176or that invokes a click command you will be given a warning.  You are177strongly encouraged to not use ``unicode_literals`` and instead use178explicit ``u`` prefixes for your Unicode strings.179180If you do want to ignore the warning and continue using181``unicode_literals`` on your own peril, you can disable the warning as182follows::183184    import click185    click.disable_unicode_literals_warning = True