Установка python linux ubuntu

Install python on Linux

Python runs on many operating systems such as MS-Windows, Mac OS, Mac OS X, Linux, FreeBSD, OpenBSD, Solaris, AIX, and many varieties of free UNIX like systems. The latest version of CentOS, Fedora, RHEL and Ubuntu come with Python 2.7 out of the box.

To see which version of Python you have install, open a command terminal and run:

Python 2.7.11 (default, Aug 9 2016, 15:45:42) 
[GCC 5.3.1 20160406 (Red Hat 5.3.1-6)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>

That is the version of python you have got and you can start building Python applications .

Use package manager

The easiest way to install the Python is to use package manger such as apt-get, yum, and so on.

Debian / Ubuntu Linux user

Use the following command to search for available versions of Python2.x under Debian and Ubuntu Linux:

$ apt-cache search python | egrep "^python2.9 " --color

Type the following command to install python version 2.x:

$ sudo apt-get install python2.6

Type the following command to install python version 3.x:

$ sudo apt-get install python3.1
Reading package lists. Done
Building dependency tree
Reading state information. Done
The following extra packages will be installed:
python3.1-minimal
Suggested packages:
python3.1-doc python3.1-profiler
The following NEW packages will be installed:
python3.1 python3.1-minimal
0 upgraded, 2 newly installed, 0 to remove and 13 not upgraded.
Need to get 5,444 kB of archives.
After this operation, 19.9 MB of additional disk space will be used.
Do you want to continue [Y/n]? y
Get:1 http://debian.osuosl.org/debian/ squeeze/main python3.1-minimal amd64 3.1.3-1 [1,669 kB]
Get:2 http://debian.osuosl.org/debian/ squeeze/main python3.1 amd64 3.1.3-1 [3,775 kB]
Fetched 5,444 kB in 27s (201 kB/s)
Selecting previously deselected package python3.1-minimal.
(Reading database . 280220 files and directories currently installed.)
Unpacking python3.1-minimal (from . /python3.1-minimal_3.1.3-1_amd64.deb) .
Selecting previously deselected package python3.1.
Unpacking python3.1 (from . /python3.1_3.1.3-1_amd64.deb) .
Processing triggers for man-db .
Processing triggers for menu .
Processing triggers for desktop-file-utils .
Processing triggers for gnome-menus .
Setting up python3.1-minimal (3.1.3-1) .
Setting up python3.1 (3.1.3-1) .
Processing triggers for menu .

Red Hat/ RHEL / CentOS Linux user

Type the following command:

From the Internet

Your can also download the version you want from the Internet.

Читайте также:  Linux сборки для разработчиков

Type the following command to download it:

$ wget --no-check-certificate https://www.python.org/ftp/python/2.7.11/Python-2.7.11.tgz

Type the folowing command to extract the file and go into the directory:

$ tar -xzf Python-2.7.11.tgz 
$ cd Python-2.7.11

Read the README file to figure out how to install, or do the following with no guarantees:

$ ./configure 
$ make
$ sudo make install

For other versions and the most up to date download links: http://www.python.org/getit/

Others

Setuptools & Pip

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

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.

Environment variable

Also add the path of new python in ‘PATH’ environment variable.

Type the following command if new python is in /root/python-2.7.4 :

$ export PATH = "$PATH":/root/python-2.7.4

Источник

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:

2.1.2. On FreeBSD and OpenBSD¶

pkg_add -r python pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages//python-.tgz
pkg_add ftp://ftp.openbsd.org/pub/OpenBSD/4.2/packages/i386/python-2.5.1p2.tgz

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:

./configure make make install

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.

Читайте также:  Putty and ssh linux

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¶

  1. 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.
$ find /etc/ -name openssl.cnf -printf "%h\n" /etc/ssl 
$ curl -O https://www.openssl.org/source/openssl-VERSION.tar.gz $ tar xzf openssl-VERSION $ pushd openssl-VERSION $ ./config \ --prefix=/usr/local/custom-openssl \ --libdir=lib \ --openssldir=/etc/ssl $ make -j1 depend $ make -j8 $ make install_sw $ popd 
$ pushd python-3.x.x $ ./configure -C \ --with-openssl=/usr/local/custom-openssl \ --with-openssl-rpath=auto \ --prefix=/usr/local/python-3.x.x $ make -j8 $ make altinstall

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.

Источник

Как скачать и установить 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 на Linux

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

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

$ apt list --installed | grep python 

Вывод списка всех версий Python на Linux Ubuntu

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

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

обновить репозиторий sudo apt-get update

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

$ sudo apt-get upgrade python3 

обновить python 3 до последней версии на ubuntu

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

Читайте также:  Sed linux точное совпадение

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

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

Проверяем текущую версию Python на Linux

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

$ sudo apt-get install python3 

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

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

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

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

$ wget https://www.python.org/ftp/python/3.7.1/Python-3.7.1.tgz 

Скачать python на Linux

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

Распаковка архива Python

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

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

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

настройка Python в Ubuntu

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

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

Запуск команды make для сборки Python 3

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

установка языка программирования Python

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

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

1. Zipimport.zipimporterror

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

ошибка zipimport.zipimporterror: can

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

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

$ sudo apt install zlib1g-dev 

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

2. No module named ‘_ctypes’

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

Ошибка No module named _ctypes

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

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

$ sudo apt-get install libffi-dev 

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

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

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

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

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

$ sudo apt-get upgrade python3 

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

обновление версии python для команды python3

Заключение

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

Источник

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