Python ������ ��� linux

Installing Python 3 on Linux¶

This document describes how to install Python 3.6 or 3.8 on Ubuntu Linux machines.

To see which version of Python 3 you have installed, open a command prompt and run

If you are using Ubuntu 16.10 or newer, then you can easily install Python 3.6 with the following commands:

If you’re using another version of Ubuntu (e.g. the latest LTS release) or you want to use a more current Python, we recommend using the deadsnakes PPA to install Python 3.8:

If you are using other Linux distribution, chances are you already have Python 3 pre-installed as well. If not, use your distribution’s package manager. For example on Fedora, you would use dnf :

Note that if the version of the python3 package is not recent enough for you, there may be ways of installing more recent versions as well, depending on you distribution. For example installing the python3.9 package on Fedora 32 to get Python 3.9. If you are a Fedora user, you might want to read about multiple Python versions available in Fedora.

Working with Python 3¶

At this point, you may have system Python 2.7 available as well.

This might launch the Python 2 interpreter.

This will always launch the Python 3 interpreter.

Setuptools & Pip¶

The two most crucial third-party Python packages are setuptools and pip.

Once installed, you can download, install and uninstall any compliant Python software product with a single command. It also enables you to add this network installation capability to your own Python software with very little work.

Python 2.7.9 and later (on the python2 series), and Python 3.4 and later include pip by default.

To see if pip is installed, open a command prompt and run

To install pip, follow the official pip installation guide — this will automatically install the latest version of setuptools.

Note that on some Linux distributions including Ubuntu and Fedora the pip command is meant for Python 2, while the pip3 command is meant for Python 3.

However, when using virtual environments (described below), you don’t need to care about that.

Pipenv & Virtual Environments¶

The next step is to install Pipenv, so you can install dependencies and manage virtual environments.

A Virtual Environment is a tool to keep the dependencies required by different projects in separate places, by creating virtual Python environments for them. It solves the “Project X depends on version 1.x but, Project Y needs 4.x” dilemma, and keeps your global site-packages directory clean and manageable.

For example, you can work on a project which requires Django 1.10 while also maintaining a project which requires Django 1.8.

This page is a remixed version of another guide, which is available under the same license.

Читайте также:  Get ip address dhcp linux

This opinionated guide exists to provide both novice and expert Python developers a best practice handbook to the installation, configuration, and usage of Python on a daily basis.

O’Reilly Book

This guide is now available in tangible book form!

All proceeds are being directly donated to the DjangoGirls organization.

Источник

Как скачать и установить Python 3 на Ubuntu 18.04 (Linux)

В этой статье мы скачаем и установим последнюю версию Python 3 на Ubuntu. Затем убедимся, что python установлен корректно, рассмотрим популярные ошибки и их решения.

Все команды выполнялись в Ubuntu 18.04 LTS, но эта статья поможет установить python на Ubuntu 16.04, Debian, Mint и другие Linux-системы.

Мы используем командную строку Ubuntu — Терминал, для работы. Вы можете открыть Терминал через поиск или комбинацию клавиш Ctrl+Alt+T.

Как проверить текущую версию Python

Проверка текущей версии программного обеспечения не только помогает вам получить номер версии этого программного обеспечения, установленного в вашей системе, но и проверяет, действительно ли программное обеспечение установлено в вашей системе.

Мы сделаем то же самое для Python, выполнив следующую команду в нашем терминале:

Версия будет отображаться, как показано в приведенном выше выводе. Число зависит от того, когда вы обновили систему.

У вас также может быть несколько версий Python, установленных в вашей системе. Следующая команда выведет список всех версий Python, которые есть в вашей системе:

Как установить Python 3 на Linux через apt-get

Установка Python 3 на Ubuntu с помощью команды apt-get довольно просто. Во-первых, вам необходимо обновить репозиторий системы, чтобы можно было установить последнюю доступную версию без проблем совместимости. Для этого выполните команду от имени администратора:

Так как Python уже установлен в нашей системе (это мы проверили в предыдущем разделе), нам нужно обновить его до последней версии следующим образом:

Система может попросить вас ввести пароль для прав sudo , поскольку только авторизованный пользователь может добавлять / удалять и обновлять программное обеспечение в Ubuntu.

Система также запросит подтверждение обновления. Введите Y , а затем нажмите Enter, чтобы продолжить.

Так вы обновили Python до последней доступной версии. Проверьте:

Если Python не установлен, вы можете установить его с правами sudo используя команду apt-get :

Как установить Python 3 на Linux из архива

Сайт Python.org содержит список всех выпусков Python по этой ссылке:
https://www.python.org/downloads/source/

Поэтому, если вы решите установить Python вручную, можете скачать python любой сборки c официального сайта. На сайте также есть последние версии, которые вы не загрузите с помощью команды apt-get .

На момент подготовки материала Python-3.7.1 последняя доступная версия, поэтому мы скачаем его файл .tgz с помощью следующей команды:

Когда архив с ptyhon будет скачан, выполните следующую команду, чтобы извлечь файлы:

После того, как файлы извлечены, нужно запустить C-программу «configure». Для этого вам необходимо установить компилятор языка программирования C — gcc в вашу Linux-систему. Если он не предустановлен, установите его с помощью следующей команды:

Измените текущую директорию на Python-3.7.1 или на ту версию python, которую вы скачали и извлекли:

Теперь используйте следующую команду, чтобы запустить скрипт конфигурации:

Теперь пришло время установить Python.

Если вы не можете запустить команду make , установите make с помощью следующей команды:

Запустите следующую команду для установки языка программирования Python:

Скачанная версия Python с официального сайта установлена ​​в вашей Linux-системе.

Ошибки, которые могут возникнуть при установке

1. Zipimport.zipimporterror

Когда вы запускаете команду sudo make install , можете столкнуться со следующей ошибкой:

Это значит, что нужно установить пакет с именем zlib1g-dev , так как он, возможно, вам не был нужен раньше.

Решение:
Выполните следующую команду с правами sudo, чтобы установить отсутствующий пакет zlib1g-dev :

Затем повторите команду для завершения установки Python:

2. No module named ‘_ctypes’

Это ошибка появляется также при запуске команды sudo make install :

Это значит, что нужно установить пакет с именем libffi-dev , так как он, возможно, вам не был нужен раньше.

Читайте также:  Apple mac with windows operating system

Решение:
Выполните следующую команду с правами sudo, чтобы установить отсутствующий пакет libffi-dev :

Затем повторите команду для завершения установки Python:

Как обновить команду python3 до последней версии

Перед установкой Python вручную из архива номер версии нашей установки Python был 3.6.7

Когда я проверил номер версии python3.7 , он дает следующий вывод:

Обновите версию python для команды python3 следующей командой:

Теперь команда python3 работает с последней версией Python в моей системе (3.7.1).

Заключение

В большинстве версий Ubuntu уже установлены Python и Pip3, но после прочтения этой статьи вы узнали, как загрузить и обновить их до последних версий.

Источник

2. Using Python on Unix platformsВ¶

2.1. Getting and installing the latest version of PythonВ¶

2.1.1. On LinuxВ¶

Python comes preinstalled on most Linux distributions, and is available as a package on all others. However there are certain features you might want to use that are not available on your distro’s package. You can easily compile the latest version of Python from source.

In the event that Python doesn’t come preinstalled and isn’t in the repositories as well, you can easily make packages for your own distro. Have a look at the following links:

for Debian users

for OpenSuse users

for Fedora users

for Slackware users

2.1.2. On FreeBSD and OpenBSDВ¶

FreeBSD users, to add the package use:

OpenBSD users, to add the package use:

For example i386 users get the 2.5.1 version of Python using:

2.1.3. On OpenSolarisВ¶

You can get Python from OpenCSW. Various versions of Python are available and can be installed with e.g. pkgutil -i python27 .

2.2. Building PythonВ¶

If you want to compile CPython yourself, first thing you should do is get the source. You can download either the latest release’s source or just grab a fresh clone. (If you want to contribute patches, you will need a clone.)

The build process consists of the usual commands:

Configuration options and caveats for specific Unix platforms are extensively documented in the README.rst file in the root of the Python source tree.

make install can overwrite or masquerade the python3 binary. make altinstall is therefore recommended instead of make install since it only installs exec_prefix /bin/python version .

These are subject to difference depending on local installation conventions; prefix ( $ ) and exec_prefix ( $ ) are installation-dependent and should be interpreted as for GNU software; they may be the same.

For example, on most Linux systems, the default for both is /usr .

Recommended location of the interpreter.

prefix /lib/python version , exec_prefix /lib/python version

Recommended locations of the directories containing the standard modules.

prefix /include/python version , exec_prefix /include/python version

Recommended locations of the directories containing the include files needed for developing Python extensions and embedding the interpreter.

2.4. MiscellaneousВ¶

To easily use Python scripts on Unix, you need to make them executable, e.g. with

and put an appropriate Shebang line at the top of the script. A good choice is usually

which searches for the Python interpreter in the whole PATH . However, some Unices may not have the env command, so you may need to hardcode /usr/bin/python3 as the interpreter path.

To use shell commands in your Python scripts, look at the subprocess module.

2.5. Custom OpenSSLВ¶

To use your vendor’s OpenSSL configuration and system trust store, locate the directory with openssl.cnf file or symlink in /etc . On most distribution the file is either in /etc/ssl or /etc/pki/tls . The directory should also contain a cert.pem file and/or a certs directory.

Download, build, and install OpenSSL. Make sure you use install_sw and not install . The install_sw target does not override openssl.cnf .

Читайте также:  Диалоговые окна windows назначение основные элементы

Build Python with custom OpenSSL (see the configure –with-openssl and –with-openssl-rpath options)

Patch releases of OpenSSL have a backwards compatible ABI. You don’t need to recompile Python to update OpenSSL. It’s sufficient to replace the custom OpenSSL installation with a newer version.

Источник

Download Python for Other Platforms

Python has been ported to a number of specialized and/or older platforms, listed below in alphabetical order. Note that these ports often lag well behind the latest Python release.

Python for AIX

AIX binary packages for Python3 and Python2 are provided by AIXTOOLS for no-charge. The packages are supplied in installp format (not RPM format). There are no pre-requisites other than a recent version of openssl.base.

See the AIXTOOLS wiki for additional details. The download page for Python 3 is at http://www.aixtools.net/index.php/python3 and the download page for Python 2 is at http://www.aixtools.net/index.php/python2.

For issues concerning the installation of AIXTOOLS packaging of Python please post your issue at http://forums.rootvg.net/aixtools.

`_ is a port to the `Amiga Research OS `_. Tim Ocock maintains `AmigaPython `_. Older versions of Python for the Amiga can be found at `Aminet `_. —> `_. For all Python-related stuff on BeOS, `search here `_. —>

Python for IBM i (formerly AS/400, iSeries)

Both Python 2 and Python 3 are available from IBM in RPM form. They can be installed with the yum package manager or with the IBM i Access Client Solutions product. To get started with RPM-based open source packages for IBM i, visit http://ibm.biz/ibmi-rpms.

These RPM packages require a version of IBM i in active (not extended) support. Alternatively, http://www.iseriespython.com hosts an IBM i port of Python 2.7, ported by Per Gummedal, which can also be run on older versions of the operating system.

Python for iOS and iPadOS

Pythonista is a complete development environment for writing Python scripts including third-party libraries and system integration on your iPad or iPhone.

Pyto also provides a complete development environment for running Python 3 including many third-party libraries and system integration on an iPad or iPhone.

`_. —> `_, built on the DJGPP platform, is also available. —> `_. —>

Python for OS/390 and z/OS

Rocket Software provides a port of Python for z/OS. They support both Python 2 and Python 3.

`_. —> `__ once completed a port of Python to the Sony PlayStation 2. Contact him for more info. —> `__. It has most modules running and can even use the PSP’s built in wifi, albeit awkwardly. —> `_. —> `_ —>

Python for RISC OS

Python is available for RISC OS, and can be obtained using the PackMan package manager.

`__ can be found at archive.org. This page also includes some pre-ported external libraries as well as RISC OS specific extensions and documentation, written by Dietmar Schwertberger. —> `_. There are downloads available at ` `_. —>

Python for Solaris

You can purchase ActivePython (commercial and community versions, including scientific computing modules, not open source), or build from source if you have a C compiler.

UNIX Packages has a variety of Python versions for a variety of Solaris versions. These use the standard Sun pkgadd.

Python for VMS

A VMS port is available.

Python for HP-UX

You can purchase ActivePython (commercial and community versions, including scientific computing modules, not open source)

Alternate Python packages for Linux

You can purchase ActivePython (commercial and community versions, including scientific computing modules, not open source)

The PSF

The Python Software Foundation is the organization behind Python. Become a member of the PSF and help advance the software and our mission.

Источник

Оцените статью