python3.rst
This file
Path
docs/python3.rst
191 lines · 7.8 KiB
Last changed by
Merge branch '7.x'David Lordbefore adoption2269786
History of this fileTake it
The walk stopped after 200 commits: lines older than ae5386b point at it.
Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
lines 1–8why, one step back1Python 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 andMerge pull request #976 from lepture/patch-versionsDavid Lordbefore adoption6149432
line 9why, one step back9Python 3.4 or higher.Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
lines 10–119why, one step back1011.. _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 switchnew docs linksDavid Lordbefore adoption7818f30
line 120why, one step back120 to Python 2 or consult the Python 3 section of the docs forChangelog for #557Markus Unterwaditzerbefore adoptionae5386b
lines 121–122why, one step back121 mitigation steps.122Merge branch '7.x'David Lordbefore adoption2269786
lines 123–128why, one step back123.. 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.128Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
lines 129–155why, one step back129You 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 encodingMerge branch '7.x'David Lordbefore adoption11abf2b
line 156why, one step back156 <https://bugs.python.org/issue13643#msg149941>`_Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
line 157why, one step back157* `Use surrogateescape as default error handlerMerge branch '7.x'David Lordbefore adoption11abf2b
line 158why, one step back158 <https://bugs.python.org/issue19977>`_Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
line 159why, one step back159* `Python 3 raises Unicode errors in the C localeMerge branch '7.x'David Lordbefore adoption11abf2b
line 160why, one step back160 <https://bugs.python.org/issue19846>`_Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
line 161why, one step back161* `LC_CTYPE=C: pydoc leaves terminal in an unusable stateMerge branch '7.x'David Lordbefore adoption11abf2b
line 162why, one step back162 <https://bugs.python.org/issue21398>`_ (this is relevant to ClickChangelog for #557Markus Unterwaditzerbefore adoptionae5386b
lines 163–164why, one step back163 because the pager support is provided by the stdlib pydoc module)164Merge branch '7.x'David Lordbefore adoptiona438322
lines 165–169why, one step back165Note (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.169Changelog for #557Markus Unterwaditzerbefore adoptionae5386b
lines 170–191why, one step back170Unicode 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