Difference between revisions of "Python"

From ArchWiki
Jump to navigation Jump to search
(→‎Package management: python2-pipenv was dropped)
 
(165 intermediate revisions by 62 users not shown)
Line 1: Line 1:
[[Category:Programming language]]
+
[[Category:Programming languages]]
 +
[[bg:Python]]
 
[[de:Python]]
 
[[de:Python]]
[[zh-CN:Python]]
+
[[es:Python]]
 +
[[ja:Python]]
 +
[[ko:Python]]
 +
[[ru:Python]]
 +
[[zh-hans:Python]]
 
{{Related articles start}}
 
{{Related articles start}}
{{Related|Python Package Guidelines}}
+
{{Related|Python package guidelines}}
{{Related|mod_python}}
+
{{Related|Python/Virtual environment}}
{{Related|Python VirtualEnv}}
+
{{Related|mod_wsgi}}
 +
{{Related|Django}}
 
{{Related articles end}}
 
{{Related articles end}}
[http://www.python.org Python] "is a remarkably powerful dynamic programming language that is used in a wide variety of application domains. Python is often compared to Tcl, Perl, Ruby, Scheme or Java."
+
From [[Wikipedia:Python (programming language)|Wikipedia]]:
  
==Installation==
+
:Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable writing clear programs on both a small and large scale.
 +
:Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.
  
There are currently two versions of Python: Python 3 (which is the default) and the older Python 2.
+
== Installation ==
  
===Python 3===
+
=== Python 3 ===
  
Python 3 is the latest version of the language, and is '''incompatible with Python 2'''. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. Also, the standard library has been reorganized in a few prominent places. For an overview of the differences, visit [http://wiki.python.org/moin/Python2orPython3 Python2orPython3] and their relevant [http://getpython3.com/diveintopython3/porting-code-to-python-3-with-2to3.html chapter] in Dive into Python 3.
+
Python 3 is the latest version of the language, and is incompatible with Python 2. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. Also, the standard library has been reorganized in a few prominent places. For an overview of the differences, visit [https://wiki.python.org/moin/Python2orPython3 Python2orPython3] and the relevant [http://getpython3.com/diveintopython3/porting-code-to-python-3-with-2to3.html chapter] in Dive into Python 3.
  
To install the latest version of Python 3, [[pacman|install]] the {{Pkg|python}} package from the [[Official Repositories|official repositories]].
+
To install the latest version of Python 3, [[install]] the {{Pkg|python}} package.
  
If you would like to build the latest RC/betas from source, visit [http://www.python.org/download/ Python Downloads]. The [[Arch User Repository]] also contains good [[PKGBUILD]]s. If you do decide to build the RC, note that the binary (by default) installs to {{ic|/usr/local/bin/python3.x}}.
+
If you would like to build the latest RC/betas from source, visit [https://www.python.org/downloads/ Python Downloads]. The [[Arch User Repository]] also contains good [[PKGBUILD]]s. If you do decide to build the RC, note that the binary (by default) installs to {{ic|/usr/local/bin/python3.x}}.
  
===Python 2===
+
=== Python 2 ===
To install the latest version of Python 2, [[pacman|install]] the {{Pkg|python2}} package from the [[Official Repositories|official repositories]].
 
  
Python 2 will happily run alongside Python 3. You need to specify '''python2''' in order to run this version.
+
To get the latest version of Python 2, [[install]] the {{Pkg|python2}} package.
  
Any program requiring Python 2 needs to point to {{ic|/usr/bin/python2}}, instead of {{ic|/usr/bin/python}}, which points to Python 3.
+
Python 2 will happily run alongside Python 3. You need to specify {{ic|python2}} in order to run this version.
  
To do so, open the program or script in a text editor and change the first line.
+
Any program requiring Python 2 needs to point to {{ic|/usr/bin/python2}}, instead of {{ic|/usr/bin/python}}, which points to Python 3. To do so, open the program or script in a [[List of applications/Documents#Text editors|text editor]] and change the first line. The line will show one of the following:
  
The line will show one of the following:
 
 
  #!/usr/bin/env python
 
  #!/usr/bin/env python
 +
 
or
 
or
 +
 
  #!/usr/bin/python
 
  #!/usr/bin/python
  
 
In both cases, just change {{ic|python}} to {{ic|python2}} and the program will then use Python 2 instead of Python 3.
 
In both cases, just change {{ic|python}} to {{ic|python2}} and the program will then use Python 2 instead of Python 3.
  
Another way to force the use of python2 without altering the scripts is to call it explicitely with python2, i.e.
+
Another way to force the use of python2 without altering the scripts is to call it explicitly with {{ic|python2}}:
{{bc|python2 myScript.py}}
+
 
 +
$ python2 ''myScript.py''
 +
 
 +
Finally, you may not be able to control the script calls, but there is a way to trick the environment. It only works if the scripts use {{ic|#!/usr/bin/env python}}. It will not work with  {{ic|#!/usr/bin/python}}. This trick relies on {{ic|env}} searching for the first corresponding entry in the {{ic|PATH}} variable.
 +
 
 +
First create a dummy folder:
  
<span id="python2_as_python">Finally,</span> you may not be able to control the script calls, but there is a way to trick the environment. It only works if the scripts use  {{ic|#!/usr/bin/env python}}, it won't work with  {{ic|#!/usr/bin/python}}. This trick relies on {{ic|env}} searching for the first corresponding entry in the PATH variable.
 
First create a dummy folder.
 
 
  $ mkdir ~/bin
 
  $ mkdir ~/bin
Then add a symlink 'python' to python2 and the config scripts in it.
+
 
 +
Then add a symlink {{ic|python}} to ''python2'' and the config scripts in it:
 +
 
 
  $ ln -s /usr/bin/python2 ~/bin/python
 
  $ ln -s /usr/bin/python2 ~/bin/python
 
  $ ln -s /usr/bin/python2-config ~/bin/python-config
 
  $ ln -s /usr/bin/python2-config ~/bin/python-config
Finally put the new folder ''at the beginning'' of your PATH variable.
+
 
 +
Finally put the new folder ''at the beginning'' of your {{ic|PATH}} variable:
 +
 
 
  $ export PATH=~/bin:$PATH
 
  $ export PATH=~/bin:$PATH
Note that this change is not permanent and is only active in the current terminal session.
+
 
 +
{{Note|This method of changing [[environment variables]] is not permanent and is only active in the current terminal session.}}
 +
 
 
To check which python interpreter is being used by {{ic|env}}, use the following command:
 
To check which python interpreter is being used by {{ic|env}}, use the following command:
 +
 
  $ which python
 
  $ which python
  
A similar approach in tricking the environment, which also relies on {{ic|#!/usr/bin/env python}} to be called by the script in question, is to use a [[Virtualenv]]. When a Virtualenv is activated, the Python executable pointed to by {{ic|$PATH}} will be the one the Virtualenv was installed with. Therefore, if the Virtualenv is installed with Python 2, {{ic|python}} will refer to Python 2. To start, [[pacman|install]] {{pkg|python2-virtualenv}}.
+
A similar approach in tricking the environment, which also relies on {{ic|#!/usr/bin/env python}} to be called by the script in question, is to use a [[#Virtual environment|virtual environment]].
# pacman -S python2-virtualenv
 
Then create the Virtualenv.
 
$ virtualenv2 venv # Creates a directory, venv/, containing the Virtualenv
 
Activate the Virtualenv, which will update {{ic|$PATH}} to point at Python 2. Note that this activation is only active for the current terminal session.
 
$ source venv/bin/activate
 
The desired script should then run using Python 2.
 
  
==Dealing with version problem in build scripts==
+
=== Alternative implementations ===
Many projects' build scripts assume {{ic|python}} to be Python 2, and that would eventually result in an error - typically complaining that {{ic|print 'foo'}} is invalid syntax. Luckily, many of them call {{ic|python}} in the {{ic|$PATH}} instead of hardcoding {{ic|#!/usr/bin/python}} in the shebang line, and the Python scripts are all contained within the project tree. So, instead of modifying the build scripts manually, there is an easy workaround. Just create {{ic|/usr/local/bin/python}} with content like this:
 
  
{{hc|/usr/local/bin/python|<nowiki>
+
Sections above refer to the reference implementation of Python, called CPython. However, there are also other implementations available - the most popular ones:
#!/bin/bash
+
 
script=`readlink -f -- "$1"`
+
* [[PyPy]] is a Python 2.7/3.5 implementation utilizing a JIT compiler. It is generally faster and uses less memory, but is not fully compatible with CPython (although the majority of packages and code will work without any changes).
case "$script" in (/path/to/project1/*|/path/to/project2/*|/path/to/project3*)
+
* [http://www.jython.org/ Jython] is a Python 2.7 implementation built in Java. It allows easy integration of Python and Java code, but is not fully compatible with CPython libraries. It is often used to provide Python as a scripting language in a bigger Java application.
    exec python2 "$@"
+
* [http://ironpython.net/ IronPython] is a Python 2.7 implementation built in .NET - it achieves the same goals as Jython, but for .NET languages (like C#/VB).
    ;;
+
* [https://micropython.org/ MicroPython] is a limited Python 3.4 implementation targeting microcontrollers and other embedded environments (like UEFI), but is incompatible with most standard packages due to [http://docs.micropython.org/en/latest/pyboard/genrst/index.html minor syntax changes and severely limited standard library]. It is often used for prototyping in with embedded environments (as it provides a Python REPL).
esac
+
* [[wikipedia:Python_(programming_language)#Implementations|More implementations are available]], although most are no longer maintained due to improvements in the most popular ones.
 +
 
 +
=== Old versions ===
 +
 
 +
{{warning|Python versions before 2.7 and 3.4 have not received any updates&mdash;including security patches&mdash;since at least 2014. Using older versions for Internet-facing applications or untrusted code may be dangerous and is not recommended.}}
 +
 
 +
Old versions of Python are available via the [[AUR]] and may be useful for historical curiosity, old applications that do not run on current versions, or for testing Python programs intended to run on a distribution that comes with an older version:
  
script=`readlink -f -- "$2"`
+
* Python 3.6: {{AUR|python36}}
case "$script" in (/path/to/project1/*|/path/to/project2/*|/path/to/project3*)
+
* Python 3.5: {{AUR|python35}}
    exec python2 "$@"
+
* Python 3.4: {{AUR|python34}}
    ;;
+
* Python 2.6: {{AUR|python26}}
esac
+
* Python 2.5: {{AUR|python25}}
 +
* Python 1.5: {{AUR|python15}}
  
exec python3 "$@"
+
Extra modules/libraries for old versions of Python may be found on the AUR by searching for {{ic|python<''version without period''>}}, e.g. searching for "python26" for 2.6 modules.
</nowiki>
 
}}
 
  
Where {{ic|<nowiki>/path/to/project1/*|/path/to/project2/*|/path/to/project3*</nowiki>}} is a list of patterns separated by {{ic|<nowiki>|</nowiki>}} matching all project trees.
+
== Package management ==
  
Don't forget to make it executable:
+
Although a great number of Python packages are readily available in the [[official repositories]] and the [[AUR]], the Python ecosystem provides its own package managers for use with [https://pypi.org/ PyPI], the Python Package Index:
  
# chmod +x /usr/local/bin/python
+
* {{App|pip|The PyPA tool for installing Python packages.|https://pip.pypa.io/|{{Pkg|python-pip}}, {{Pkg|python2-pip}}}}
 +
* {{App|setuptools|Easily download, build, install, upgrade, and uninstall Python packages.|https://setuptools.readthedocs.io/|{{Pkg|python-setuptools}}, {{Pkg|python2-setuptools}}}}
  
Afterwards scripts within the specified project trees will be run with Python 2.
+
For a brief history and feature comparison between the two, see [https://packaging.python.org/pip_easy_install/#pip-vs-easy-install pip vs easy_install]. Authoritative best practices in Python package management are detailed [https://packaging.python.org/ here].
  
==Integrated Development Environments==
+
If you must use ''pip'', use a [[#Virtual environment|virtual environment]], or {{ic|pip install --user}} to avoid conflicts with packages in {{ic|/usr}}. It is always preferred to [[System maintenance#Use the package manager to install software|use pacman to install software]].
There are some IDEs for Python available in the [[Official Repositories|official repositories]].
 
  
===Eclipse===
+
{{Note|There are also tools integrating ''pip'' with ''pacman'' by automatically generating PKGBUILDs for specified pip-packages: see [[Creating packages#PKGBUILD generators]].}}
  
Eclipse supports both Python 2.x and 3.x series by using the [[Eclipse#PyDev|PyDev]] extension.
+
{{Tip|[https://docs.pipenv.org/ pipenv] provides a single CLI for [https://github.com/pypa/pipfile Pipfile], ''pip'' and [[virtualenv]]. It is available as {{Pkg|python-pipenv}}.}}
  
===Eric===
+
== Widget bindings ==
For the latest Python 3 compatible version, [[pacman|install]] the {{Pkg|eric}} package.
 
  
Version 4 of Eric is Python 2 compatible and can be installed with the {{Pkg|eric4}} package.
+
The following [[Wikipedia:Widget toolkit|widget toolkit]] bindings are available:
  
These IDEs can also handle [[Ruby]].
+
* {{App|TkInter|Tk bindings|https://wiki.python.org/moin/TkInter|standard module}}
 +
* {{App|pyQt|[[Qt]] bindings|https://riverbankcomputing.com/software/pyqt/intro|{{AUR|python2-pyqt4}} {{Pkg|python2-pyqt5}} {{AUR|python-pyqt4}} {{Pkg|python-pyqt5}}}}
 +
* {{App|pySide2|[[Qt]] bindings|https://wiki.qt.io/PySide2|{{Pkg|pyside2}} {{Pkg|pyside2-tools}}}}
 +
* {{App|pyGTK|[[GTK|GTK 2]] bindings|http://www.pygtk.org/|{{Pkg|pygtk}}}}
 +
* {{App|PyGObject|[[GTK|GTK 2/3]] bindings via GObject Introspection|https://wiki.gnome.org/PyGObject/|{{Pkg|python2-gobject2}} {{Pkg|python2-gobject}} {{Pkg|python-gobject2}} {{Pkg|python-gobject}}}}
 +
* {{App|wxPython|wxWidgets bindings|https://wxpython.org/|{{Pkg|python2-wxpython3}} {{Pkg|python-wxpython}}}}
  
===IEP===
+
To use these with Python, you may need to install the associated widget kits.
  
IEP is an interactive (e.g. MATLAB) python IDE with basic debugging capabilities and is especially suitable for scientific computing. It is provided by the package {{AUR|iep}}.
+
== Tips and tricks ==
  
===Ninja===
+
=== Alternative shells ===
  
The Ninja IDE is provided by the package {{Pkg|ninja-ide}}.
+
* {{App|bpython|Fancy interface for the Python interpreter.|https://bpython-interpreter.org/|{{Pkg|bpython}} {{Pkg|bpython2}}}}
 +
* {{App|[[Wikipedia:IPython|IPython]]|Enhanced interactive Python shell.|https://ipython.org/|{{Pkg|ipython}} {{Pkg|ipython2}}}}
 +
* {{App|[[Jupyter]] Notebook|Web interface to IPython.|https://jupyter.org/|{{Pkg|jupyter-notebook}}}}
 +
* {{App|ptpython|Fancy interface for the Python interpreter based on [https://github.com/jonathanslenders/python-prompt-toolkit prompt-toolkit] input interface.|https://github.com/jonathanslenders/ptpython|{{aur|ptpython}} {{aur|ptpython2}}}}
  
===Spyder===
+
=== Virtual environment ===
  
Spyder (previously known as Pydee) is a powerful interactive development environment for the Python language with advanced editing, interactive testing, debugging and introspection features. It focuses on scientific computations, providing a matlab-like environment. It can be installed with the package {{AUR|spyder}}
+
Python provides tools to create isolated environments in which you can install packages without interfering with the other virtual environments nor with the system Python's packages. It could change the ''python'' interpreter used for a specific application.  
  
== Getting easy_install ==
+
See [[Python/Virtual environment]] for details.
  
The easy_install tool is available in the package {{Pkg|python-setuptools}}.
+
=== Tab completion in Python shell ===
  
 +
Since Python 3.4 [https://docs.python.org/3/tutorial/interactive.html tab completion] is enabled by default, for Python 2 you can manually enable it by adding the following lines to a file referenced by the {{ic|PYTHONSTARTUP}} environment variable: [https://docs.python.org/2/library/rlcompleter.html]
  
== Getting completion in Python shell ==
+
import rlcompleter
 +
import readline
 +
readline.parse_and_bind("tab: complete")
  
Copy this into Python's interactive shell
+
Note that readline completer will only complete names in the global namespace. You can rely on {{Pkg|python-jedi}} and/or {{Pkg|python2-jedi}} for a more richer tab completion experience [https://jedi.readthedocs.io/en/latest/docs/usage.html#tab-completion-in-the-python-shell].
{{hc|/usr/bin/python|<nowiki>
 
import rlcompleter
 
import readline
 
readline.parse_and_bind("tab: complete")
 
</nowiki>
 
}}
 
[http://algorithmicallyrandom.blogspot.com.es/2009/09/tab-completion-in-python-shell-how-to.html Source]
 
  
==Widget bindings ==
+
== Troubleshooting ==
The following [[wikipedia:widget toolkit|widget toolkit]] bindings are available:
+
=== Dealing with version problem in build scripts ===
*{{App|TkInter|Tk bindings|http://wiki.python.org/moin/TkInter|standard module}}
 
*{{App|pyQt|[[Qt]] bindings|http://www.riverbankcomputing.co.uk/software/pyqt/intro|{{Pkg|python2-pyqt4}} {{Pkg|python2-pyqt5}} {{Pkg|python-pyqt4}} {{Pkg|python-pyqt5}}}}
 
*{{App|pySide|[[Qt]] bindings|http://www.pyside.org/|{{AUR|python2-pyside}} {{AUR|python-pyside}}}}
 
*{{App|pyGTK|[[GTK+|GTK+ 2]] bindings|http://www.pygtk.org/|{{Pkg|pygtk}}}}
 
*{{App|PyGObject|[[GTK+|GTK+ 2/3]] bindings via GObject Introspection|https://wiki.gnome.org/PyGObject/|{{Pkg|python2-gobject2}} {{Pkg|python2-gobject}} {{Pkg|python-gobject2}} {{Pkg|python-gobject}}}}
 
*{{App|wxPython|wxWidgets bindings|http://wxpython.org/|{{Pkg|wxpython}}}}
 
To use these with Python, you may need to install the associated widget kits.
 
  
==Old versions==
+
{{Style|This is an ugly hack, instead explain how to recursively fix shebangs with {{ic|find}} and {{ic|sed}}.}}
Old versions of Python are available via the [[Arch User Repository|AUR]] and may be useful for historical curiosity, old applications that don't run on current versions, or for testing Python programs intended to run on a distribution that comes with an older version (eg, RHEL 5.x has Python 2.4, or Ubuntu 12.04 has Python 3.1):
 
*{{AUR|python15}}: Python 1.5.2
 
*{{AUR|python16}}: Python 1.6.1
 
*{{AUR|python24}}: Python 2.4.6
 
*{{AUR|python25}}: Python 2.5.6
 
*{{AUR|python26}}: Python 2.6.8
 
*{{AUR|python30}}: Python 3.0.1
 
*{{AUR|python31}}: Python 3.1.5
 
*{{AUR|python32}}: Python 3.2.3
 
  
As of November 2012, Python upstream only supports Python 2.6, 2.7, 3.1, 3.2, and 3.3 for security fixes.  Using older versions for Internet-facing applications or untrusted code may be dangerous and is not recommended.
+
Many projects' build scripts assume {{ic|python}} to be Python 2, and that would eventually result in an error — typically complaining that {{ic|print 'foo'}} is invalid syntax. Luckily, many of them call ''python'' from the {{ic|PATH}} environment variable instead of hardcoding {{ic|#!/usr/bin/python}} in the shebang line, and the Python scripts are all contained within the project tree. So, instead of modifying the build scripts manually, there is a workaround. Create {{ic|/usr/local/bin/python}} with content like this:
  
Extra modules/libraries for old versions of Python may be found on the AUR by searching for python(version without decimal), eg searching for "python26" for 2.6 modules.
+
{{hc|/usr/local/bin/python|<nowiki>
 +
#!/bin/bash
 +
script=$(readlink -f -- "$1")
 +
case "$script" in (/path/to/project1/*|/path/to/project2/*|/path/to/project3*)
 +
    exec python2 "$@"
 +
    ;;
 +
esac
  
==More Resources==
+
exec python3 "$@"
* [http://shop.oreilly.com/product/9780596158071.do Learning Python] is one of the most comprehensive, up to date, and well-written books on Python available today.
+
</nowiki>}}
* [http://www.diveintopython.net/ Dive Into Python] is an excellent (free) resource, but perhaps for more advanced readers and [http://diveintopython3.ep.io/ has been updated for Python 3].
 
* [http://www.swaroopch.com/notes/Python A Byte of Python] is a book suitable for users new to Python (and scripting in general).
 
* [http://learnpythonthehardway.org Learn Python The Hard Way] the best intro to programming.
 
* [http://facts.learnpython.org facts.learnpython.org] nice site to learn python.
 
* [http://stephensugden.com/crash_into_python/ Crash into Python] Also known as ''Python for Programmers with 3 Hours'', this guide gives experienced developers from other languages a crash course on Python.
 
* [http://www.apress.com/book/view/9781590598726 Beginning Game Development with Python and Pygame: From Novice to Professional] for games
 
  
==For Fun==
+
Where {{ic|<nowiki>/path/to/project1/*|/path/to/project2/*|/path/to/project3*</nowiki>}} is a list of patterns separated by {{ic|<nowiki>|</nowiki>}} matching all project trees. For some scripts, the path may not be the first parameter, for example Google SDK it sends "-S" as the first parameter. The readlink command should change to {{ic|1=script=$(readlink -f -- "$1")}}.
Try the following snippets from Python's interactive shell:
 
  
>>> import this
+
Do not forget to make it [[executable]]. Afterwards scripts within the specified project trees will be run with Python 2.
  
>>> from __future__ import braces
+
== See also ==
  
>>> import antigravity
+
* [http://shop.oreilly.com/product/0636920028154.do O'Reilly's Learning Python, 5th edition] commercial
 +
* [http://www.diveintopython.net/ Dive Into Python], [http://getpython3.com/diveintopython3/ Dive Into Python3]
 +
* [https://python.swaroopch.com/ A Byte of Python]
 +
* [https://learnpythonthehardway.org/ Learn Python the Hard Way]
 +
* [https://learnpython.org/ Learn Python]
 +
* [https://stephensugden.com/crash_into_python/ Crash into Python] (assumes familiarity with other programming languages)
 +
* [https://www.apress.com/book/9781590598726 Beginning Game Development with Python and Pygame] commercial
 +
* [http://www.greenteapress.com/thinkpython/ Think Python]
 +
* [https://pythonspot.com Pythonspot]
 +
* [https://overiq.com/python/3.4/intro-to-python/ OverIQ Python Tutorial]
 +
* [https://www.techbeamers.com/python-tutorial-step-by-step/ Python Tutorial to Learn Step by Step]
 +
* [https://github.com/vinta/awesome-python awesome-python] - A curated list of Python frameworks, libraries, software and resources.
 +
* [https://github.com/mahmoud/boltons boltons] - Constructs/recipes/snippets that would be handy in the standard library.

Latest revision as of 10:29, 15 October 2019

From Wikipedia:

Python is a widely used high-level, general-purpose, interpreted, dynamic programming language. Its design philosophy emphasizes code readability, and its syntax allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable writing clear programs on both a small and large scale.
Python supports multiple programming paradigms, including object-oriented, imperative and functional programming or procedural styles. It features a dynamic type system and automatic memory management and has a large and comprehensive standard library.

Installation

Python 3

Python 3 is the latest version of the language, and is incompatible with Python 2. The language is mostly the same, but many details, especially how built-in objects like dictionaries and strings work, have changed considerably, and a lot of deprecated features have finally been removed. Also, the standard library has been reorganized in a few prominent places. For an overview of the differences, visit Python2orPython3 and the relevant chapter in Dive into Python 3.

To install the latest version of Python 3, install the python package.

If you would like to build the latest RC/betas from source, visit Python Downloads. The Arch User Repository also contains good PKGBUILDs. If you do decide to build the RC, note that the binary (by default) installs to /usr/local/bin/python3.x.

Python 2

To get the latest version of Python 2, install the python2 package.

Python 2 will happily run alongside Python 3. You need to specify python2 in order to run this version.

Any program requiring Python 2 needs to point to /usr/bin/python2, instead of /usr/bin/python, which points to Python 3. To do so, open the program or script in a text editor and change the first line. The line will show one of the following:

#!/usr/bin/env python

or

#!/usr/bin/python

In both cases, just change python to python2 and the program will then use Python 2 instead of Python 3.

Another way to force the use of python2 without altering the scripts is to call it explicitly with python2:

$ python2 myScript.py

Finally, you may not be able to control the script calls, but there is a way to trick the environment. It only works if the scripts use #!/usr/bin/env python. It will not work with #!/usr/bin/python. This trick relies on env searching for the first corresponding entry in the PATH variable.

First create a dummy folder:

$ mkdir ~/bin

Then add a symlink python to python2 and the config scripts in it:

$ ln -s /usr/bin/python2 ~/bin/python
$ ln -s /usr/bin/python2-config ~/bin/python-config

Finally put the new folder at the beginning of your PATH variable:

$ export PATH=~/bin:$PATH
Note: This method of changing environment variables is not permanent and is only active in the current terminal session.

To check which python interpreter is being used by env, use the following command:

$ which python

A similar approach in tricking the environment, which also relies on #!/usr/bin/env python to be called by the script in question, is to use a virtual environment.

Alternative implementations

Sections above refer to the reference implementation of Python, called CPython. However, there are also other implementations available - the most popular ones:

  • PyPy is a Python 2.7/3.5 implementation utilizing a JIT compiler. It is generally faster and uses less memory, but is not fully compatible with CPython (although the majority of packages and code will work without any changes).
  • Jython is a Python 2.7 implementation built in Java. It allows easy integration of Python and Java code, but is not fully compatible with CPython libraries. It is often used to provide Python as a scripting language in a bigger Java application.
  • IronPython is a Python 2.7 implementation built in .NET - it achieves the same goals as Jython, but for .NET languages (like C#/VB).
  • MicroPython is a limited Python 3.4 implementation targeting microcontrollers and other embedded environments (like UEFI), but is incompatible with most standard packages due to minor syntax changes and severely limited standard library. It is often used for prototyping in with embedded environments (as it provides a Python REPL).
  • More implementations are available, although most are no longer maintained due to improvements in the most popular ones.

Old versions

Warning: Python versions before 2.7 and 3.4 have not received any updates—including security patches—since at least 2014. Using older versions for Internet-facing applications or untrusted code may be dangerous and is not recommended.

Old versions of Python are available via the AUR and may be useful for historical curiosity, old applications that do not run on current versions, or for testing Python programs intended to run on a distribution that comes with an older version:

Extra modules/libraries for old versions of Python may be found on the AUR by searching for python<version without period>, e.g. searching for "python26" for 2.6 modules.

Package management

Although a great number of Python packages are readily available in the official repositories and the AUR, the Python ecosystem provides its own package managers for use with PyPI, the Python Package Index:

  • pip — The PyPA tool for installing Python packages.
https://pip.pypa.io/ || python-pip, python2-pip
  • setuptools — Easily download, build, install, upgrade, and uninstall Python packages.
https://setuptools.readthedocs.io/ || python-setuptools, python2-setuptools

For a brief history and feature comparison between the two, see pip vs easy_install. Authoritative best practices in Python package management are detailed here.

If you must use pip, use a virtual environment, or pip install --user to avoid conflicts with packages in /usr. It is always preferred to use pacman to install software.

Note: There are also tools integrating pip with pacman by automatically generating PKGBUILDs for specified pip-packages: see Creating packages#PKGBUILD generators.
Tip: pipenv provides a single CLI for Pipfile, pip and virtualenv. It is available as python-pipenv.

Widget bindings

The following widget toolkit bindings are available:

  • TkInter — Tk bindings
https://wiki.python.org/moin/TkInter || standard module
  • pyQtQt bindings
https://riverbankcomputing.com/software/pyqt/intro || python2-pyqt4AUR python2-pyqt5 python-pyqt4AUR python-pyqt5
  • pySide2Qt bindings
https://wiki.qt.io/PySide2 || pyside2 pyside2-tools
http://www.pygtk.org/ || pygtk
  • PyGObjectGTK 2/3 bindings via GObject Introspection
https://wiki.gnome.org/PyGObject/ || python2-gobject2 python2-gobject python-gobject2 python-gobject
  • wxPython — wxWidgets bindings
https://wxpython.org/ || python2-wxpython3 python-wxpython

To use these with Python, you may need to install the associated widget kits.

Tips and tricks

Alternative shells

  • bpython — Fancy interface for the Python interpreter.
https://bpython-interpreter.org/ || bpython bpython2
  • IPython — Enhanced interactive Python shell.
https://ipython.org/ || ipython ipython2
  • Jupyter Notebook — Web interface to IPython.
https://jupyter.org/ || jupyter-notebook
  • ptpython — Fancy interface for the Python interpreter based on prompt-toolkit input interface.
https://github.com/jonathanslenders/ptpython || ptpythonAUR ptpython2AUR

Virtual environment

Python provides tools to create isolated environments in which you can install packages without interfering with the other virtual environments nor with the system Python's packages. It could change the python interpreter used for a specific application.

See Python/Virtual environment for details.

Tab completion in Python shell

Since Python 3.4 tab completion is enabled by default, for Python 2 you can manually enable it by adding the following lines to a file referenced by the PYTHONSTARTUP environment variable: [1]

import rlcompleter
import readline
readline.parse_and_bind("tab: complete")

Note that readline completer will only complete names in the global namespace. You can rely on python-jedi and/or python2-jedi for a more richer tab completion experience [2].

Troubleshooting

Dealing with version problem in build scripts

Tango-edit-clear.pngThis article or section needs language, wiki syntax or style improvements. See Help:Style for reference.Tango-edit-clear.png

Reason: This is an ugly hack, instead explain how to recursively fix shebangs with find and sed. (Discuss in Talk:Python#)

Many projects' build scripts assume python to be Python 2, and that would eventually result in an error — typically complaining that print 'foo' is invalid syntax. Luckily, many of them call python from the PATH environment variable instead of hardcoding #!/usr/bin/python in the shebang line, and the Python scripts are all contained within the project tree. So, instead of modifying the build scripts manually, there is a workaround. Create /usr/local/bin/python with content like this:

/usr/local/bin/python
#!/bin/bash
script=$(readlink -f -- "$1")
case "$script" in (/path/to/project1/*|/path/to/project2/*|/path/to/project3*)
    exec python2 "$@"
    ;;
esac

exec python3 "$@"

Where /path/to/project1/*|/path/to/project2/*|/path/to/project3* is a list of patterns separated by | matching all project trees. For some scripts, the path may not be the first parameter, for example Google SDK it sends "-S" as the first parameter. The readlink command should change to script=$(readlink -f -- "$1").

Do not forget to make it executable. Afterwards scripts within the specified project trees will be run with Python 2.

See also