Arch linux and python

Python package guidelines

This document covers standards and guidelines on writing PKGBUILDs for Python software.

Package naming

For Python 3 library modules, use python-modulename . Also use the prefix if the package provides a program that is strongly coupled to the Python ecosystem (e.g. pip or tox). For other applications, use only the program name.

Architecture

A Python package that contains C extensions is architecture-dependent. Otherwise it is most likely architecture-independent.

Packages built using setuptools define their C extensions using the ext_modules keyword in setup.py .

Source

Download URLs linked from the PyPI website include an unpredictable hash that needs to be fetched from the PyPI website each time a package must be updated. This makes them unsuitable for use in a PKGBUILD. PyPI provides an alternative stable scheme: PKGBUILD#source source=() array should use the following URL templates:

Note that a custom _name variable is used instead of pkgname since Python packages are generally prefixed with python- . This variable can generically be defined as follows:

Installation methods

Python packages are generally installed using language-specific package manager such as pip, which fetches packages from an online repository (usually PyPI, the Python Package Index) and tracks the relevant files.

However, for managing Python packages from within PKGBUILD s, one needs to «install» the Python package to the temporary location $pkgdir/usr/lib/python /site-packages/$pkgname .

For Python packages using standard metadata to specify their build backend in pyproject.toml , this can most easily achieved using python-build and python-installer . Old packages might fail to specify that they use setuptools, and only offer a setup.py that has to be invoked manually.

Note: Dependencies from the package’s metadata must be defined in the depends array otherwise they will not be installed.

Standards based (PEP 517)

A standards based workflow is straightforward: Build a wheel using python-build and install it to $pkgdir using python-installer :

makedepends=(python-build python-installer python-wheel) build() < cd "$_name-$pkgver" python -m build --wheel --no-isolation >package() < cd "$_name-$pkgver" python -m installer --destdir="$pkgdir" dist/*.whl >
  • —wheel results in only a wheel file to be built, no source distribution.
  • —no-isolation means that the package is built using what is installed on your system (which includes packages you specified in depends ), by default the tool creates an isolated virtual environment and performs the build there.
  • —destdir=»$pkgdir» prevents trying to directly install in the host system instead of inside the package file, which would result in a permission error
  • —compile-bytecode=. or —no-compile-bytecode can be passed to installer , but the default is sensibly picked, so this should not be necessary.
Читайте также:  Sp flash tool linux mint

Warning: Skipping build and putting the .whl file in your source array is discouraged in favor of building from source, and should only be used when the latter is not a viable option (for example, packages which only come with wheel sources, and therefore cannot be built from source).

Warning: If your package is a VCS package ( python-…-git ), include the command git -C «$/$» clean -dfx in your prepare function. This removes stale wheels along with other build artifacts, and helps prevent issues further down the road. See also upstream issues for setuptools and Poetry.

setuptools or distutils

If no pyproject.toml can be found or it fails to contain a [build-system] table, it means the project is using the old legacy format, which uses a setup.py file which invokes setuptools or distutils. Note that while distutils is included in Python’s standardlib, having setuptools installed means that you use a patched version of distutils.

makedepends=(‘python-setuptools’) # unless it only requires distutils build() < cd "$_name-$pkgver" python setup.py build >package()

  • —root=»$pkgdir» works like —destdir above
  • —optimize=1 compiles optimized bytecode files (.opt-1.pyc) so they can be tracked by pacman instead of being created on the host system on demand.
  • Adding —skip-build optimizes away the unnecessary attempt to re-run the build steps already run in the build() function, if that is the case.

If the resulting package includes executables which import the deprecated pkg_resources module, then setuptools must be additionally specified as a depends in the split package_*() functions; alternatively, if the PKGBUILD only installs the Python package for a single version of Python, setuptools should be moved from makedepends to depends .

Some packages try to use setuptools and fall back to distutils if setuptools could not be imported. In this case, setuptools should be added as a makedepends , so that the resulting Python metadata is better.

If a package needs setuptools to be built due to including executables (which is not supported by distutils), but only imports distutils, then building will raise a warning, and the resulting package will be broken (it will not contain the executables):

/usr/lib/python3.8/distutils/dist.py:274: UserWarning: Unknown distribution option: 'entry_points' warnings.warn(msg)

An upstream bug should be reported. To work around the problem, an undocumented setuptools feature can be used:

# fails because of distutils python setup.py build # works by using a setuptools shim python -m setuptools.launch setup.py build

If a package uses python-setuptools-scm , the package most likely will not build with an error such as:

LookupError: setuptools-scm was unable to detect version for /build/python-jsonschema/src/jsonschema-3.2.0. Make sure you're either building from a fully intact git repository or PyPI tarballs. Most other sources (such as GitHub's tarballs, a git checkout without the .git folder) don't contain the necessary metadata and will not work.

To get it building SETUPTOOLS_SCM_PRETEND_VERSION has to be exported as an environment variable with $pkgver as the value:

export SETUPTOOLS_SCM_PRETEND_VERSION=$pkgver

Check

Warning: Avoid using tox to run testsuites as it is explicitly designed to test repeatable configurations downloaded from PyPI while tox is running, and does not test the version that will be installed by the package. This defeats the purpose of having a check function at all.

Читайте также:  Linux tar list file

Most Python projects providing a testsuite use nosetests or pytest to run tests with test in the name of the file or directory containing the testsuite. In general, simply running nosetests or pytest is enough to run the testsuite.

If there is a compiled C extension, the tests need to be run using a $PYTHONPATH , that reflects the current major and minor version of Python in order to find and load it.

check()< cd "$pkgname-$pkgver" local python_version=$(python -c 'import sys; print("".join(map(str, sys.version_info[:2])))') # For nosetests PYTHONPATH="$PWD/build/lib.linux-$CARCH-cpython-$" nosetests # For pytest PYTHONPATH="$PWD/build/lib.linux-$CARCH-cpython-$" pytest >

Some projects provide setup.py entry points for running the test. This works for both pytest and nosetests .

Tips and tricks

Discovering detached PGP signatures on PyPI

If detached PGP signatures for a given Python sdist tarball exist, they should be used to verify the tarball. However, the signature files do not show up directly in the files download section of any given project on pypi.org. To discover the sdist tarballs and their potential signature files, it is possible to use this service to get an overview per project: https://pypi.debian.net/

Using python version

Sometimes during preparing, building, testing or installation it is required to refer to the system’s major and minor Python version. Do not hardcode this (e.g. 3.9 or 3.10 ) and instead use a call to the Python interpreter to retrieve the information and store it in a local variable:

Using site-packages

Sometimes during building, testing or installation it is required to refer to the system’s site-packages directory. Do not hardcode this directory and use a call to the Python interpreter instead to retrieve the path and store it in a local variable:

Test directory in site-package

Make sure to not install a directory named just tests into site-packages (i.e. /usr/lib/pythonX.Y/site-packages/tests/ ). Python package projects using setuptools are sometimes misconfigured to include the directory containing its tests as a top level Python package. If you encounter this, you can help by filing an issue with the package project and ask them to fix this, e.g. like this.

  • This page was last edited on 21 June 2023, at 09:51.
  • Content is available under GNU Free Documentation License 1.3 or later unless otherwise noted.
  • Privacy policy
  • About ArchWiki
  • Disclaimers

Источник

Python (Русский)/Virtual environment (Русский)

Состояние перевода: На этой странице представлен перевод статьи Python/Virtual environment. Дата последней синхронизации: 28 мая 2023. Вы можете помочь синхронизировать перевод, если в английской версии произошли изменения.

virtualenv — это инструмент, используемый для создания изолированного рабочего пространства для приложения Python. Он даёт некоторые преимущества: например, возможность локальной установки модулей, экспорта рабочей среды и выполнения программы Python внутри этого окружения.

Читайте также:  Mono install linux ubuntu

Обзор

Виртуальное окружение (virtual environment) — это каталог, в который устанавливаются некоторые исполняемые файлы и скрипты. Среди файлов есть python для выполнения скриптов и pip для установки других модулей в окружении. Также есть скрипты для активации окружения в различных командных оболочках (для bash, csh и fish). По сути, виртуальное окружение имитирует полную системную установку Python и всех необходимых модулей, не вмешиваясь в работу системы, на которой будет запускаться приложение.

В 2017 году был опубликован Pipenv, который управляет всеми вышеперечисленными инструментами: виртуальными окружениями интерпретаторов python, зависимостями пакетов, их активацией и блокировкой версий в Pipfile.

Установка

Python 3.3+ поставляется с модулем venv. Для более старых версий Python можно использовать сторонний инструмент virtualenv.

Пакеты

Установите один из следующих пакетов:

Использование

Все три инструмента похожи.

Создание

Используйте venv или virtualenv для создания виртуального окружения в каталоге вашего проекта. Не забудьте исключить каталог venv из вашей системы контроля версий — для его восстановления достаточно копии pip freeze .

venv

$ python -m venv envname 

virtualenv

Активация

Для активации виртуального окружения используйте один из имеющихся скриптов для вашей командной оболочки. Пример для bash:

$ source envname/bin/activate (envname) $

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

Для выхода из виртуального окружения выполните функцию, которую создал скрипт активации:

Версии Python

По умолчанию виртуальные окружения создаются с использованием стандартного системного Python. Файл bin/python — это просто символическая ссылка на системный python:

$ ls -l envname/bin/python lrwxrwxrwx 1 foo foo 15 янв 29 18:48 envname/bin/python -> /usr/bin/python

Если вы хотите использовать другую версию Python внутри виртуального окружения, можно использовать опцию -p / —python у virtualenv:

$ virtualenv -p 3.8 envname $ ls -l envname/bin/python lrwxrwxrwx 1 foo foo 18 янв 29 18:48 envname/bin/python -> /usr/bin/python3.8
$ virtualenv -p pypy3 envname 

virtualenvwrapper

virtualenvwrapper позволяет более удобно управлять виртуальными окружениями через командную строку, предоставляя несколько полезных команд для создания, активации и удаления виртуальных окружений. Этот пакет является обёрткой для python-virtualenv .

Установка

export WORKON_HOME=~/.virtualenvs source /usr/bin/virtualenvwrapper.sh

Строка source /usr/bin/virtualenvwrapper.sh может несколько замедлить запуск новой командной оболочки. Для решения проблемы можно использовать source /usr/bin/virtualenvwrapper_lazy.sh , который загрузит virtualenvwrapper только при первом обращении к нему.

Перезапустите консоль для применения изменений. Каталог WORKON_HOME будет создан автоматически.

Использование

Подробности можно почитать в официальной документации.

Создание виртуального окружения (все опции командной строки, кроме -a , -i , -r и -h , передаются в virtualenv, так что можно использовать опцию -p для выбора нужной версии Python):

$ mkvirtualenv envname 

Активация виртуального окружения:

Установка пакета внутри виртуального окружения (скажем, Django):

(envname) $ pip install django

Выход из виртуального окружения:

Pipenv

pipenv упрощает управление через командную строку, предоставляя одну программу, которая выполняет все функции вышеперечисленных инструментов.

Установка

Использование

Все команды можно выполнять в папке проекта, и pipenv распознает текущую ситуацию — найдёт виртуальное окружение в текущем каталоге и будет использовать его.

Подробности в документации: [1], [2], [3].

Смотрите также

Источник

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