- 2. Using Python on Unix platforms¶
- 2.1. Getting and installing the latest version of Python¶
- 2.1.1. On Linux¶
- 2.1.2. On FreeBSD and OpenBSD¶
- 2.1.3. On OpenSolaris¶
- 2.2. Building Python¶
- 2.3. Python-related paths and files¶
- 2.4. Miscellaneous¶
- 2.5. Custom OpenSSL¶
- Сборка и установка Python 3 из исходников (Ubuntu, Debian).
- Загрузка исходников.
- Конфигурирование, сборка и установка.
- Установка основных зависимостей для сборки Python3:
- Установка всех зависимостей для полной сборки и установки Python3:
- Install Python From Source#
- Install required dependencies#
- Specify Python version#
- Download and extract Python#
- Build and install Python#
- Install pip and virtualenv#
- Verify Python installation#
- (Optional) Add Python to the system PATH#
- (Optional) Install multiple versions of Python#
- Installing OR-Tools Python from Source on Linux
- Introduction
- Prerequisites
- C++ tools
- Alpine Edge
- Centos 8
- Debian 10
- Ubuntu 21.04
- Ubuntu 20.04 LTS
- Ubuntu 18.04 LTS
- Alpine Edge
- Centos 8
- Debian 10
- Ubuntu 21.04
- Ubuntu 20.04 LTS
- Ubuntu 18.04 LTS
- Python
- Alpine Edge
- Centos 8
- Debian 10
- Ubuntu 21.04
- Ubuntu 20.04 LTS
- Ubuntu 18.04 LTS
- Download the source code
- Download the stable source code
- Download the master source code
- Download previous releases
- Build third parties
- Using SCIP
- Using Gurobi
- Using an optional third-party MIP solver
- Build the source code
- Test the source code
- Cleaning the build files
- Installing OR-Tools on your operating system
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 .
2.3. Python-related paths and files¶
These are subject to difference depending on local installation conventions; prefix ( $
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 .
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.
Источник
Сборка и установка Python 3 из исходников (Ubuntu, Debian).
Загрузка исходников.
- переходим на страницу загрузки Python v.3 официального сайта языка программирования Python;
- выбираем нужную Вам версию Python из столбика «Release version», жмем на ссылку.
- открывшуюся страницу прокручиваем вниз и загружаем исходники Python — «Gzipped source tarball», которые будем компилировать.
Конфигурирование, сборка и установка.
Для основного интерпретатора CPython требуется только компилятор языка C, НО для некоторых модулей стандартной библиотеки Python (например, модуль сжатия zlib или модуль базы данных sqlite3 ) потребуются установить дополнительные системные библиотеки.
Установка основных зависимостей для сборки Python3:
Примечание: команда установки sudo apt install . записана в 3 строки, что бы уместить библиотеки на экране без горизонтальной прокрутки.Обратите внимание, что это только основные зависимости, для успешной сборки Python
Установка всех зависимостей для полной сборки и установки Python3:
Применительно к Debian, Ubuntu и других систем на базе установщика apt .
Во-первых, убедитесь, что в списке источников sources.list включены пакеты с исходными кодами. Это можно сделать, добавив строку с расположением scr пакетов, включая URL-адрес, имя дистрибутива и имя компонента в файл /etc/apt/sources.list .
Затем вы должны обновить индекс пакетов и установить зависимости сборки через команду apt :
Если этот пакет недоступен в вашей системе, то попробуйте уменьшить версию до тех пор, пока не найдете доступный пакет. Например:
Внимание! Если пакет для сборки, например Python3.8 недоступен в вашем дистрибутиве (а доступен только например Python3.6), то это не значит что версию Python3.8 нельзя установить в вашу систему. Просто некоторые модули стандартной библиотеки Python используют системную библиотеку версией выше и ее нет в вашем дистрибутиве. В итоге модуль использующий библиотеку, которой нет, просто не скомпилируется и не будет работать в итоговой сборке.
И так, имеем скачанный Python нужной версии, допустим это будет версия 3.x.x (x — цифры нужной версии ), в формате GZIP и с расширением .tgz . Распакуем архив с исходниками Python-3.x.x.tgz, при этом создастся папка Python-3.x.x, в которую затем перейдем.
Теперь нужно сконфигурировать установку командой ./configure . Определимся, куда мы будем ставить нужный нам Python и укажем этот директорий в конфигурации. Обычно не системные приложения в Linux ставятся в папку /opt , следовательно, будем ставить в директорию /opt/Python-3.x.x/ , где .x.x — обозначают версию Python.
- Включение флага —enable-optimizations позволяет оптимизировать профилирование PGO — оптимизация профиля [лучшая подготовка, поддержка llvm и т.д.] и оптимизацию LTO — времени связи для GCC и CLANG. Оба являются дорогостоящими оптимизациями, которые замедляют процесс сборки, но дают значительное повышение скорости примерно на 10-20%.
- Включение флага —with-lto использует возможность последних наборов инструментов компилятора для оптимизации через произвольную границу файла .o при создании окончательных исполняемых файлов или общих библиотек для дополнительного повышения производительности.
- Для поддержки часового пояса по умолчанию, начиная с версии Python 3.9, при компиляции можно указать флаг —with-tzpath , который должен быть строкой, разделенной os.pathsep и указывать на данные о часовых поясах в системе.
- Все флаги конфигурации можно посмотреть командой ./configure -help .
Далее скомпилируем Python и установим в директорию, указанную в конфигурации:
Команда make -c -j4 создаст CPython с выводом только предупреждений и ошибок в stderr и будет использовать до 2-x ядер ЦП. Если вы используете машину с более чем четырьмя ядрами или одноядерную машину, то измените число, переданное в флаг -j, в соответствии с количеством ядер, которые у вас есть
После удачной установки, для удобного вызова Python, добавим aliases для текущей сессии терминала:
После закрытия терминала созданные нами aliases удалятся. Что бы создать постоянные aliases, добавим их в файл Вашего профиля .basrc
И все же, при установке сторонних модулей и пакетов, мы все еще пользуемся привилегиями суперпользователя sudo , а это в системах Linux не приветствуется.
Чтобы избежать этого и других неприятных ситуаций, а так же пользоваться Python согласно «религии» и по «фен шуй», нужно перенести его экземпляр в виртуальное окружение.
Источник
Install Python From Source#
These instructions describe how to install Python from source on a Linux server.
Install required dependencies#
First, enable the optional and required repositories by following the steps here.
Next, use the following commands to install the dependencies required to build and run Python for your Linux distribution.
Specify Python version#
Specify the version of Python that you want to install:
A list of available Python versions can be found on python.org.
Download and extract Python#
Download and extract Python, then navigate into the Python directory:
Build and install Python#
Configure, make, and install Python:
Install pip and virtualenv#
Install pip and virtualenv into the version of Python that you just installed:
Verify Python installation#
Verify that Python is installed by running the following command:
(Optional) Add Python to the system PATH#
You can configure Python on the system PATH so that users can use pip within a terminal to install packages to their home directory, similar to how R works with install.packages() .
The recommended method to add Python to the PATH is to append the version of Python that you installed to the system-wide PATH variable. For example, this can be defined in a script within the /etc/profile.d/ directory:
is the version of Python that you installed earlier.
(Optional) Install multiple versions of Python#
If you want to install multiple versions of Python on the same server, you can repeat these steps to specify, download, and install a different version of Python alongside existing versions.
Источник
Installing OR-Tools Python from Source on Linux
Introduction
This guide explains how to install OR-Tools from source, with support for Python, on Linux. Unless you plan to modify the source code or use a third-party solver with OR-Tools, we recommend the binary installation.
Although these instructions might also work on other Linux variants, we have only tested them on machines meeting the following requirements:
- Ubuntu 21.04/20.04 LTS/18.04 LTS/16.04 LTS 64-bit (x86_64)
- Alpine Edge 64-bit (x86_64)
- Centos 7 64-bit (x86_64)
- Centos 8 64-bit (x86_64)
- Debian 10.10 (buster) 64-bit (x86_64)
- Debian 11.0 (bullseye) 64-bit (x86_64)
- Fedora 33 64-bit (x86_64)
- Fedora 34 64-bit (x86_64)
Note: OR-Tools only supports the x86-64 (also known as amd64) architecture.
Prerequisites
The following sections describe the prerequisites for installing OR-Tools from source.
C++ tools
To install C++ tools, open a terminal window and enter:
Alpine Edge
Centos 8
Debian 10
Ubuntu 21.04
Ubuntu 20.04 LTS
Ubuntu 18.04 LTS
To install SWIG, open a terminal window and enter:
Alpine Edge
Centos 8
Debian 10
Ubuntu 21.04
Ubuntu 20.04 LTS
Ubuntu 18.04 LTS
Python
You must have Python 3.6+ installed.
To install Python 3.6+, open a terminal window and enter:
Alpine Edge
Centos 8
Debian 10
Ubuntu 21.04
Ubuntu 20.04 LTS
Ubuntu 18.04 LTS
You can check your Python 3 installation using:
Download the source code
There are two distinct branches of the OR-Tools source code on GitHub: stable and master. The stable branch has been thoroughly tested and should work flawlessly on all supported platforms. The master branch is where the latest updates and improvements have been applied; it’s more current, but less stable.
Download the stable source code
You can get the stable source code for OR-Tools in either of the following ways:
- Clone the stable branch by entering
- Download the latest release in a compressed file, by clicking the Clone or download button in GitHub.
Warning: The full path to the installation directory (where you extract the files) must not contain any spaces.
Download the master source code
To retrieve the source code from the master branch, enter
Download previous releases
You can get the source code for previous releases in either of the following ways:
- Download a previous release from the GitHub release page.
- Assuming you have already created a local repository (by git clone ), you can check out a specific release using a Git tag. For example, to work with the v9.1 release instead of the master branch, enter the following commands in your local repo:
Build third parties
Before building OR-Tools, you’ll need to build the required third party software.
Open a terminal and navigate to the directory where you extracted the files. Then enter:
Using SCIP
Since v7.8, SCIP is now integrated so you won’t have to install it manually. Warning:While OR-Tools ships with SCIP, please consult the SCIP license to ensure that you are complying with it.
Using Gurobi
Gurobi is now pre-integrated. When needed, at runtime, OR-Tools will search for the Gurobi shared library in the default install path of the Gurobi installers on MAC OS X and Windows, or by using the GUROBI_HOME environment variable.
Using an optional third-party MIP solver
You can also use OR-Tools with any of the following optional third-party MIP solvers whose support is disabled by default:
To configure OR-Tools to use one of these solvers, do the following steps:
- Install the optional solver following the vendor instruction.
- Open Makefile.local and add the path to the directory where you have installed the solver. For example, for CPLEX you would add this:
Build the source code
To build the source code, open a terminal and navigate to the directory where you extracted the files. Then enter the following command to compile OR-Tools:
Test the source code
You can check that everything is running correctly by entering:
This runs a selection of examples for OR-Tools. If all the examples run successfully, you are ready to get started with OR-Tools.
Cleaning the build files
If you need to re-install OR-Tools, the command:
will remove all compiled dependencies and Makefile.local . This can be useful for resetting to a clean state.
Then re-enter the commands
Installing OR-Tools on your operating system
You can install OR-Tools for Python on your operating system by entering
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Источник