Movatterモバイル変換


[0]ホーム

URL:


Following system colour schemeSelected dark colour schemeSelected light colour scheme

Python Enhancement Proposals

PEP 394 – The “python” Command on Unix-Like Systems

Author:
Kerrick Staley <mail at kerrickstaley.com>,Alyssa Coghlan <ncoghlan at gmail.com>,Barry Warsaw <barry at python.org>,Petr Viktorin <encukou at gmail.com>,Miro Hrončok <miro at hroncok.cz>,Carol Willing <willingc at gmail.com>
Status:
Active
Type:
Informational
Created:
02-Mar-2011
Post-History:
04-Mar-2011, 20-Jul-2011, 16-Feb-2012, 30-Sep-2014, 28-Apr-2018,26-Jun-2019
Resolution:
Python-Dev message

Table of Contents

Abstract

This PEP outlines the behavior of Python scripts when thepython commandis invoked.Depending on a distribution or system configuration,python may or may not be installed.Ifpython is installed its target interpreter may refer topython2orpython3.End users may be unaware of this inconsistency across Unix-like systems.This PEP’s goal is to reduce user confusion about whatpython referencesand what will be the script’s behavior.

The recommendations in the next section of this PEP will outline the behaviorwhen:

  • using virtual environments
  • writing cross-platform scripts with shebangs for eitherpython2 orpython3

The PEP’s goal is to clarify the behavior for script end users, distributionproviders, and script maintainers / authors.

Recommendation

Our recommendations are detailed below.We call out any expectations that these recommendations are based upon.

For Python runtime distributors

  • We expect Unix-like software distributions (including systems like macOS andCygwin) to install thepython2 command into the default pathwhenever a version of the Python 2 interpreter is installed, and the sameforpython3 and the Python 3 interpreter.
  • When invoked,python2 should run some version of the Python 2interpreter, andpython3 should run some version of the Python 3interpreter.
  • If thepython command is installed, it is expected to invoke eitherthe same version of Python as thepython3 command or as thepython2command.
  • Distributors may choose to set the behavior of thepython commandas follows:
    • python2,
    • python3,
    • not providepython command,allowpython to be configurable by an end user ora system administrator.
  • The Python 3.xidle,pydoc, andpython-config commands shouldlikewise be available asidle3,pydoc3, andpython3-config;Python 2.x versions asidle2,pydoc2, andpython2-config.The commands with no version number should either invoke the same versionof Python as thepython command, or not be available at all.
  • When packaging third party Python scripts, distributors are encouraged tochange less specific shebangs to more specific ones.This ensures software is used with the latest version of Python available,and it can remove a dependency on Python 2.The details on what specifics to set are left to the distributors;though. Example specifics could include:
    • Changingpython shebangs topython3 when Python 3.x is supported.
    • Changingpython shebangs topython2 when Python 3.x is not yetsupported.
    • Changingpython3 shebangs topython3.8 if the software is builtwith Python 3.8.
  • When a virtual environment (created by thePEP 405venv package or asimilar tool such asvirtualenv orconda) is active, thepythoncommand should refer to the virtual environment’s interpreter and shouldalways be available.Thepython3 orpython2 command (according to the environment’sinterpreter version) should also be available.

For Python script publishers

  • When reinvoking the interpreter from a Python script, queryingsys.executable to avoid hardcoded assumptions regarding theinterpreter location remains the preferred approach.
  • Encourage your end users to use a virtual environment.This makes the user’s environment more predictable (possibly resultingin fewer issues), and helps avoid disrupting their system.
  • For scripts that are only expected to be run in an activated virtualenvironment, shebang lines can be written as#!/usr/bin/envpython,as this instructs the script to respect the active virtual environment.
  • In cases where the script is expected to be executed outside virtualenvironments, developers will need to be aware of the followingdiscrepancies across platforms and installation methods:
    • Older Linux distributions will provide apython command thatrefers to Python 2, and will likely not provide apython2 command.
    • Some newer Linux distributions will provide apython command thatrefers to Python 3.
    • Some Linux distributions will not provide apython command atall by default, but will provide apython3 command by default.
  • When potentially targeting these environments, developers may eitheruse a Python package installation tool that rewrites shebang lines forthe installed environment, provide instructions on updating shebang linesinteractively, or else use more specific shebang lines that aretailored to the target environment.
  • Scripts targeting both “old systems” and systems without the defaultpython command need to make a compromise and document this situation.Avoiding shebangs (via the console_scripts Entry Points ([9]) or similarmeans) is the recommended workaround for this problem.
  • Applications designed exclusively for a specific environment (such asa container or virtual environment) may continue to use thepythoncommand name.

For end users of Python

  • While far from being universally available,python remains thepreferred spelling for explicitly invoking Python, as this is thespelling that virtual environments make consistently availableacross different platforms and Python installations.
  • For software that is not distributed with (or developed for) your system,we recommend using a virtual environment, possibly with an environmentmanager likeconda orpipenv, to help avoid disrupting your systemPython installation.

These recommendations are the outcome of the relevant python-dev discussionsin March and July 2011 ([1],[2]), February 2012 ([4]),September 2014 ([6]), discussion on GitHub in April 2018 ([7]),on python-dev in February 2019 ([8]), and during the PEP update reviewin May/June 2019 ([10]).

History of this PEP

In 2011, the majority of distributionsaliased thepython command to Python 2, but some started switching it toPython 3 ([5]). As some of the former distributions did not provide apython2 command by default, there was previously no way for Python 2 code(or any code that invokes the Python 2 interpreter directly rather than viasys.executable) to reliably run on all Unix-like systems withoutmodification, as thepython command would invoke the wrong interpreterversion on some systems, and thepython2 command would fail completelyon others. This PEP originally provided a very simple mechanismto restore cross-platform support, with minimal additional work requiredon the part of distribution maintainers. Simplified, the recommendation was:

  1. Thepython command was preferred for code compatible with bothPython 2 and 3 (since it was available on all systems, even those thatalready aliased it to Python 3).
  2. Thepython command should always invoke Python 2 (to preventhard-to-diagnose errors when Python 2 code is run on Python 3).
  3. Thepython2 andpython3 commands should be available to specifythe version explicitly.

However, these recommendations implicitly assumed that Python 2 would always beavailable. As Python 2 is nearing its end of life in 2020 (PEP 373,PEP 404),distributions are making Python 2 optional or removing it entirely.This means either removing thepython command or switching it to invokePython 3. Some distributors also decided that their users were better served byignoring the PEP’s original recommendations, and provided systemadministrators with the freedom to configure their systems based onthe needs of their particular environment.

Current Rationale

As of 2019, activating a Python virtual environment (or its functionalequivalent) prior to script execution is one way to obtain a consistentcross-platform and cross-distribution experience.

Accordingly, publishers can expect users of the software to provide a suitableexecution environment.

Future Changes to this Recommendation

This recommendation will be periodically reviewed over the next few years,and updated when the core development team judges it appropriate. As apoint of reference, regular maintenance releases for the Python 2.7 serieswill continue until January 2020.

Migration Notes

This section does not contain any official recommendations from the coreCPython developers. It’s merely a collection of notes regarding variousaspects of migrating to Python 3 as the default version of Python for asystem. They will hopefully be helpful to any distributions consideringmaking such a change.

  • The main barrier to a distribution switching thepython command frompython2 topython3 isn’t breakage within the distribution, butinstead breakage of private third party scripts developed by sysadminsand other users. Updating thepython command to invokepython3by default indicates that a distribution is willing to break such scriptswith errors that are potentially quite confusing for users that aren’tfamiliar with the backwards incompatible changes in Python 3. Forexample, while the change ofprint from a statement to a builtinfunction is relatively simple for automated converters to handle, theSyntaxError from attempting to use the Python 2 notation in Python 3may be confusing for users that are not aware of the change:
    $ python3 -c 'print "Hello, world!"'  File"<string>", line1print"Hello, world!"^SyntaxError:Missing parentheses in call to 'print'. Did you mean print("Hello, world!")?

    While this might be obvious for experienced Pythonistas, such scriptsmight even be run by people who are not familiar with Python at all.Avoiding breakage of such third party scripts was the key reason thisPEP used to recommend thatpython continue to refer topython2.

  • The error messagepython:commandnotfound tends to be surprisinglyactionable, even for people unfamiliar with Python.
  • ThepythonX.X (e.g.python3.6) commands exist on modern systems, onwhich they invoke specific minor versions of the Python interpreter. Itcan be useful for distribution-specific packages to take advantage of theseutilities if they exist, since it will prevent code breakage if the defaultminor version of a given major version is changed. However, scriptsintending to be cross-platform should not rely on the presence of theseutilities, but rather should be tested on several recent minor versions ofthe target major version, compensating, if necessary, for the smalldifferences that exist between minor versions. This prevents the need forsysadmins to install many very similar versions of the interpreter.
  • When thepythonX.X binaries are provided by a distribution, thepython2 andpython3 commands should refer to one of those filesrather than being provided as a separate binary file.
  • It is strongly encouraged that distribution-specific packages usepython3(orpython2) rather thanpython, even in code that is not intended tooperate on other distributions. This will reduce problems if thedistribution later decides to change the version of the Python interpreterthat thepython command invokes, or if a sysadmin installs a custompython command with a different major version than the distributiondefault.
  • If the above point is adhered to and sysadmins are permitted to change thepython command, then thepython command should always be implementedas a link to the interpreter binary (or a link to a link) and not viceversa. That way, if a sysadmin does decide to replace the installedpython file, they can do so without inadvertently deleting thepreviously installed binary.
  • Even as the Python 2 interpreter becomes less common, it remains reasonablefor scripts to continue to use thepython3 convention, rather than justpython.
  • If these conventions are adhered to, it will become the case that thepython command is only executed in an interactive manner as a userconvenience, or else when using a virtual environment or similar mechanism.

Backwards Compatibility

A potential problem can arise if a script adhering to thepython2/python3 convention is executed on a system not supportingthese commands. This is mostly a non-issue, since the sysadmin can simplycreate these symbolic links and avoid further problems. It is a significantlymore obvious breakage than the sometimes cryptic errors that can arise whenattempting to execute a script containing Python 2 specific syntax with aPython 3 interpreter or vice versa.

Application to the CPython Reference Interpreter

While technically a new feature, themakeinstall andmakebininstallcommand in the 2.7 version of CPython were adjusted to create thefollowing chains of symbolic links in the relevantbin directory (thefinal item listed in the chain is the actual installed binary, precedingitems are relative symbolic links):

python -> python2 -> python2.7python-config -> python2-config -> python2.7-config

Similar adjustments were made to the macOS binary installer.

This feature first appeared in the default installation process inCPython 2.7.3.

The installation commands in the CPython 3.x series already create theappropriate symlinks. For example, CPython 3.2 creates:

python3 -> python3.2idle3 -> idle3.2pydoc3 -> pydoc3.2python3-config -> python3.2-config

And CPython 3.3 creates:

python3 -> python3.3idle3 -> idle3.3pydoc3 -> pydoc3.3python3-config -> python3.3-configpysetup3 -> pysetup3.3

The implementation progress of these features in the default installers wasmanaged on the tracker as issue #12627 ([3]).

Impact on PYTHON* Environment Variables

The choice of target for thepython command implicitly affects adistribution’s expected interpretation of the various Python relatedenvironment variables. The use of*.pth files in the relevantsite-packages folder, the “per-user site packages” feature (seepython-msite) or more flexible tools such asvirtualenv are all moretolerant of the presence of multiple versions of Python on a system than thedirect use ofPYTHONPATH.

Exclusion of MS Windows

This PEP deliberately excludes any proposals relating to Microsoft Windows, asdevising an equivalent solution for Windows was deemed too complex to handlehere.PEP 397 and the related discussion on the python-dev mailing listaddress this issue.

References

[1]
Support the /usr/bin/python2 symlink upstream (with bonus grammar class!)(https://mail.python.org/pipermail/python-dev/2011-March/108491.html)
[2]
Rebooting PEP 394 (aka Support the /usr/bin/python2 symlink upstream)(https://mail.python.org/pipermail/python-dev/2011-July/112322.html)
[3]
Implement PEP 394 in the CPython Makefile(https://github.com/python/cpython/issues/56836)
[4]
PEP 394 request for pronouncement (python2 symlink in *nix systems)(https://mail.python.org/pipermail/python-dev/2012-February/116435.html)
[5]
Arch Linux announcement that their “python” link now refers Python 3(https://www.archlinux.org/news/python-is-now-python-3/)
[6]
PEP 394 - Clarification of what “python” command should invoke(https://mail.python.org/pipermail/python-dev/2014-September/136374.html)
[7]
PEP 394: Allow thepython command to not be installed, and otherminor edits(https://github.com/python/peps/pull/630)
[8]
Another update for PEP 394 – The “python” Command on Unix-Like Systems(https://mail.python.org/pipermail/python-dev/2019-February/156272.html)
[9]
The console_scripts Entry Point(https://python-packaging.readthedocs.io/en/latest/command-line-scripts.html#the-console-scripts-entry-point)
[10]
May 2019 PEP update review(https://github.com/python/peps/pull/989)

Copyright

This document has been placed in the public domain.


Source:https://github.com/python/peps/blob/main/peps/pep-0394.rst

Last modified:2024-02-26 08:33:49 GMT


[8]ページ先頭

©2009-2025 Movatter.jp