setuptools python что это

Packaging and distributing projects¶

The section does not aim to cover best practices for Python project development as a whole. For example, it does not provide guidance or tool recommendations for version control, documentation, or testing.

For more reference material, see Building and Distributing Packages in the setuptools docs, but note that some advisory content there may be outdated. In the event of conflicts, prefer the advice in the Python Packaging User Guide.

Requirements for packaging and distributing¶

You’ll need this to upload your project distributions to PyPI (see below ).

Configuring your project¶

Initial files¶

setup.py¶

The most important file is setup.py which exists at the root of your project directory. For an example, see the setup.py in the PyPA sample project.

setup.py serves two primary functions:

setup.cfg¶

setup.cfg is an ini file that contains option defaults for setup.py commands. For an example, see the setup.cfg in the PyPA sample project.

README.rst / README.md¶

All projects should contain a readme file that covers the goal of the project. The most common format is reStructuredText with an “rst” extension, although this is not a requirement; multiple variants of Markdown are supported as well (look at setup() ’s long_description_content_type argument).

MANIFEST.in¶

A MANIFEST.in is needed when you need to package additional files that are not automatically included in a source distribution. For details on writing a MANIFEST.in file, including a list of what’s included by default, see “ Including files in source distributions with MANIFEST.in ”.

MANIFEST.in does not affect binary distributions such as wheels.

LICENSE.txt¶

Every package should include a license file detailing the terms of distribution. In many jurisdictions, packages without an explicit license can not be legally used or distributed by anyone other than the copyright holder. If you’re unsure which license to choose, you can use resources such as GitHub’s Choose a License or consult a lawyer.

For an example, see the LICENSE.txt from the PyPA sample project.

Although it’s not required, the most common practice is to include your Python modules and packages under a single top-level package that has the same name as your project, or something very close.

For an example, see the sample package that’s included in the PyPA sample project.

setup() args¶

As mentioned above, the primary feature of setup.py is that it contains a global setup() function. The keyword arguments to this function are how specific details of your project are defined.

The most relevant arguments are explained below. Most of the snippets given are taken from the setup.py contained in the PyPA sample project.

Start & end with an ASCII letter or digit.

version ¶

This is the current version of your project, allowing your users to determine whether or not they have the latest version, and to indicate which specific versions they’ve tested their own software against.

Versions are displayed on PyPI for each release if you publish your project.

See Choosing a versioning scheme for more information on ways to use versions to convey compatibility information to your users.

If the project code itself needs run-time access to the version, the simplest way is to keep the version in both setup.py and your code. If you’d rather not duplicate the value, there are a few ways to manage this. See the “ Single-sourcing the package version ” Advanced Topics section.

description ¶

Give a short and long description for your project.

description is also displayed in lists of projects. For example, it’s visible in the search results pages such as https://pypi.org/search/?q=jupyter, the front-page lists of trending projects and new releases, and the list of projects you maintain within your account profile (such as https://pypi.org/user/jaraco/).

Give a homepage URL for your project.

author ¶

Provide details about the author.

license ¶

The license argument doesn’t have to indicate the license under which your package is being released, although you may optionally do so if you want. If you’re using a standard, well-known license, then your main indication can and should be via the classifiers argument. Classifiers exist for all major open-source licenses.

The license argument is more typically used to indicate differences from well-known licenses, or to include your own, unique license. As a general rule, it’s a good idea to use a standard, well-known license, both to avoid confusion and because some organizations avoid software whose license is unapproved.

classifiers ¶

Provide a list of classifiers that categorize your project. For a full listing, see https://pypi.org/classifiers/.

Although the list of classifiers is often used to declare what Python versions a project supports, this information is only used for searching & browsing projects on PyPI, not for installing projects. To actually restrict what Python versions a project can be installed on, use the python_requires argument.

keywords ¶

List keywords that describe your project.

project_urls ¶

List additional relevant URLs about your project. This is the place to link to bug trackers, source repositories, or where to support package development. The string of the key is the exact text that will be displayed on PyPI.

packages ¶

Set packages to a list of all packages in your project, including their subpackages, sub-subpackages, etc. Although the packages can be listed manually, setuptools.find_packages() finds them automatically. Use the include keyword argument to find only the given packages. Use the exclude keyword argument to omit packages that are not intended to be released and installed.

py_modules ¶

install_requires ¶

python_requires ¶

If your project only runs on certain Python versions, setting the python_requires argument to the appropriate PEP 440 version specifier string will prevent pip from installing the project on other Python versions. For example, if your package is for Python 3+ only, write:

If your package is for Python 2.6, 2.7, and all versions of Python 3 starting with 3.3, write:

Support for this feature is relatively recent. Your project’s source distributions and wheels (see Packaging your project ) must be built using at least version 24.2.0 of setuptools in order for the python_requires argument to be recognized and the appropriate metadata generated.

In addition, only versions 9.0.0 and higher of pip recognize the python_requires metadata. Users with earlier versions of pip will be able to download & install projects on any Python version regardless of the projects’ python_requires values.

package_data ¶

The value must be a mapping from package name to a list of relative path names that should be copied into the package. The paths are interpreted as relative to the directory containing the package.

data_files ¶

Each (directory, files) pair in the sequence specifies the installation directory and the files to install there. The directory must be a relative path (although this may change in the future, see wheel Issue #92), and it is interpreted relative to the installation prefix (Python’s sys.prefix for a default installation; site.USER_BASE for a user installation). Each file name in files is interpreted relative to the setup.py script at the top of the project source distribution.

scripts ¶

Although setup() supports a scripts keyword for pointing to pre-made scripts to install, the recommended approach to achieve cross-platform compatibility is to use console_scripts entry points (see below).

entry_points ¶

Use this keyword to specify any plugins that your project provides for any named entry points that may be defined by your project or others that you depend on.

For more information, see the section on Advertising Behavior from the setuptools docs.

The most commonly used entry point is “console_scripts” (see below).

console_scripts ¶

Choosing a versioning scheme¶

Standards compliance for interoperability¶

Here are some examples of compliant version numbers:

To further accommodate historical variations in approaches to version numbering, PEP 440 also defines a comprehensive technique for version normalisation that maps variant spellings of different version numbers to a standardised canonical form.

Scheme choices¶

Semantic versioning (preferred)¶

For new projects, the recommended versioning scheme is based on Semantic Versioning, but adopts a different approach to handling pre-releases and build metadata.

The essence of semantic versioning is a 3-part MAJOR.MINOR.MAINTENANCE numbering scheme, where the project author increments:

MAJOR version when they make incompatible API changes,

MINOR version when they add functionality in a backwards-compatible manner, and

MAINTENANCE version when they make backwards-compatible bug fixes.

Adopting this approach as a project author allows users to make use of “compatible release” specifiers, where name

= X.Y requires at least release X.Y, but also allows any later release with a matching MAJOR version.

Python projects adopting semantic versioning should abide by clauses 1-8 of the Semantic Versioning 2.0.0 specification.

Date based versioning¶

Semantic versioning is not a suitable choice for all projects, such as those with a regular time based release cadence and a deprecation process that provides warnings for a number of releases prior to removal of a feature.

A key advantage of date based versioning is that it is straightforward to tell how old the base feature set of a particular release is given just the version number.

Serial versioning¶

This is the simplest possible versioning scheme, and consists of a single number which is incremented every release.

While serial versioning is very easy to manage as a developer, it is the hardest to track as an end user, as serial version numbers convey little or no information regarding API backwards compatibility.

Hybrid schemes¶

Combinations of the above schemes are possible. For example, a project may combine date based versioning with serial versioning to create a YEAR.SERIAL numbering scheme that readily conveys the approximate age of a release, but doesn’t otherwise commit to a particular release cadence within the year.

Pre-release versioning¶

Regardless of the base versioning scheme, pre-releases for a given final release may be published as:

zero or more dev releases (denoted with a “.devN” suffix)

zero or more alpha releases (denoted with a “.aN” suffix)

zero or more beta releases (denoted with a “.bN” suffix)

zero or more release candidates (denoted with a “.rcN” suffix)

pip and other modern Python package installers ignore pre-releases by default when deciding which versions of dependencies to install.

Local version identifiers¶

A local version identifier takes the form

Working in “development mode”¶

You can install a project in “editable” or “develop” mode while you’re working on it. When installed as editable, a project can be edited in-place without reinstallation: changes to Python source files in projects installed as editable will be reflected the next time an interpreter process is started.

To install a Python package in “editable”/”development” mode Change directory to the root of the project directory and run:

You may want to install some of your dependencies in editable mode as well. For example, supposing your project requires “foo” and “bar”, but you want “bar” installed from VCS in editable mode, then you could construct a requirements file like so:

The first line says to install your project and any dependencies. The second line overrides the “bar” dependency, such that it’s fulfilled from VCS, not PyPI.

If, however, you want “bar” installed from a local directory in editable mode, the requirements file should look like this, with the local paths at the top of the file:

Otherwise, the dependency will be fulfilled from PyPI, due to the installation order of the requirements file. For more on requirements files, see the Requirements File section in the pip docs. For more on VCS installs, see the VCS Support section of the pip docs.

Lastly, if you don’t want to install any dependencies at all, you can run:

Packaging your project¶

Before you can build wheels and sdists for your project, you’ll need to install the build package:

Источник

setuptools Quickstart¶

Installation¶

To install the latest version of setuptools, use:

Python packaging at a glance¶

Basic Use¶

For basic use of setuptools, you will need a pyproject.toml with the exact following info, which declares you want to use setuptools to package your project:

Then, you will need a setup.cfg or setup.py to specify your package information, such as metadata, contents, dependencies, etc. Here we demonstrate the minimum

This is what your project would look like:

Of course, before you release your project to PyPI, you’ll want to add a bit more information to your setup script to help people find or learn about your project. And maybe your project will have grown by then to include a few dependencies, and perhaps some data files and scripts. In the next few sections, we will walk through the additional but essential information you need to specify to properly package your project.

Automatic package discovery¶

When you pass the above information, alongside other necessary information, setuptools walks through the directory specified in where (omitted here as the package resides in the current directory) and filters the packages it can find following the include (defaults to none), then removes those that match the exclude and returns a list of Python packages. Note that each entry in the [options.packages.find] is optional. The above setup also allows you to adopt a src/ layout. For more details and advanced use, go to Package Discovery and Namespace Package

Entry points and automatic script creation¶

Dependency management¶

When your project is installed, all of the dependencies not already installed will be located (via PyPI), downloaded, built (if necessary), and installed. This, of course, is a simplified scenarios. setuptools also provides additional keywords such as setup_requires that allows you to install dependencies before running the script, and extras_require that take care of those needed by automatically generated scripts. It also provides mechanisms to handle dependencies that are not in PyPI. For more advanced use, see Dependencies Management in Setuptools

Including Data Files¶

The distutils have traditionally allowed installation of “data files”, which are placed in a platform-specific location. Setuptools offers three ways to specify data files to be included in your packages. For the simplest use, you can simply use the include_package_data keyword:

This tells setuptools to install any data files it finds in your packages. The data files must be specified via the distutils’ MANIFEST.in file. For more details, see Data Files Support

Development mode¶

setuptools allows you to install a package without copying any files to your interpreter directory (e.g. the site-packages directory). This allows you to modify your source code and have the changes take effect without you having to rebuild and reinstall. Here’s how to do it:

Uploading your package to PyPI¶

After generating the distribution files, the next step would be to upload your distribution so others can use it. This functionality is provided by twine and we will only demonstrate the basic use here.

Transitioning from setup.py to setup.cfg ¶

Resources on Python packaging¶

Packaging in Python is hard. Here we provide a list of links for those that want to learn more.

Источник

Python. Урок 16. Установка пакетов в Python

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

Где взять отсутствующий пакет?

Менеджер пакетов в Pythonpip

Pip – это консольная утилита (без графического интерфейса). После того, как вы ее скачаете и установите, она пропишется в PATH и будет доступна для использования.

Эту утилиту можно запускать как самостоятельно:

так и через интерпретатор Python :

Установка pip

При развертывании современной версии Python (начиная с P ython 2.7.9 и Python 3.4),
pip устанавливается автоматически. Но если, по какой-то причине, pip не установлен на вашем ПК, то сделать это можно вручную. Существует несколько способов.

Обновление pip

Для Windows команда будет следующей:

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

Далее рассмотрим основные варианты использования pip : установка пакетов, удаление и обновление пакетов.

Установка пакета

Pip позволяет установить самую последнюю версию пакета, конкретную версию или воспользоваться логическим выражением, через которое можно определить, что вам, например, нужна версия не ниже указанной. Также есть поддержка установки пакетов из репозитория. Рассмотрим, как использовать эти варианты.

Установка последней версии пакета

Установка определенной версии

Установка пакета с версией не ниже 3.1

Установка Python пакета из git репозитория

Установка из альтернативного индекса

Установка пакета из локальной директории

Удаление пакета

Для того, чтобы удалить пакет воспользуйтесь командой

Обновление пакетов

Для обновления пакета используйте ключ –upgrade.

Просмотр установленных пакетов

Поиск пакета в репозитории

Где ещё можно прочитать про работу с pip?

В сети довольно много информации по работе с данной утилитой.

P.S.

Если вам интересна тема анализа данных, то мы рекомендуем ознакомиться с библиотекой Pandas. На нашем сайте вы можете найти вводные уроки по этой теме. Все уроки по библиотеке Pandas собраны в книге “Pandas. Работа с данными”.
setuptools python что это. Смотреть фото setuptools python что это. Смотреть картинку setuptools python что это. Картинка про setuptools python что это. Фото setuptools python что это

Источник

Building and Distributing Packages with Setuptools¶

Setuptools is a collection of enhancements to the Python distutils that allow developers to more easily build and distribute Python packages, especially ones that have dependencies on other packages.

Enhanced support for accessing data files hosted in zipped packages.

Automatically include all packages in your source tree, without listing them individually in setup.py

Automatically include all relevant files in your source distributions, without needing to create a MANIFEST.in file, and without having to force regeneration of the MANIFEST file when your source tree changes.

Easily extend the distutils with new commands or setup() arguments, and distribute/reuse your extensions for multiple projects, without copying code.

Create extensible applications and frameworks that automatically discover extensions, using simple “entry points” declared in a project’s setup script.

Developer’s Guide¶

TRANSITIONAL NOTE¶

Setuptools automatically calls declare_namespace() for you at runtime, but future versions may not. This is because the automatic declaration feature has some negative side effects, such as needing to import all namespace packages during the initialization of the pkg_resources runtime, and also the need for pkg_resources to be explicitly imported before any namespace packages work at all. In some future releases, you’ll be responsible for including your own declaration lines, and the automatic declaration feature will be dropped to get rid of the negative side effects.

During the remainder of the current development cycle, therefore, setuptools will warn you about missing declare_namespace() calls in your __init__.py files, and you should correct these as soon as possible before the compatibility support is removed. Namespace packages without declaration lines will not work correctly once a user has upgraded to a later version, so it’s important that you make this change now in order to avoid having your code break in the field. Our apologies for the inconvenience, and thank you for your patience.

setup.cfg-only projects¶

New in version 40.9.0.

If setup.py is missing from the project directory when a PEP 517 build is invoked, setuptools emulates a dummy setup.py file containing only a setuptools.setup() call.

To use this feature:

As PEP 517 is new, support is not universal, and frontends that do support it may still have bugs. For compatibility, you may want to put a setup.py file containing only a setuptools.setup() invocation.

Configuration API¶

Some automation tools may wish to access data from a configuration file.

Setuptools exposes a read_configuration() function for parsing metadata and options sections into a dictionary.

Mailing List and Bug Tracker¶

Please use the distutils-sig mailing list for questions and discussion about setuptools, and the setuptools bug tracker ONLY for issues you have confirmed via the list are actual bugs, and which you have reduced to a minimal set of steps to reproduce.

Источник

distutils, setuptools, pip — Python: Настройка окружения

На прошлом уроке мы познакомились с пакетами и индексами, давайте же узнаем, как устанавливать пакеты из индекса! Для установки, обновления и удаления пакетов часто применяются так называемые пакетные менеджеры (или менеджеры пакетов). Один такой мы рассмотрим, но сначала немного поговорим о фундаменте системы пакетирования Python.

distutils и setuptools

В поставку Python входит distutils, пакет, отвечающий за создание дистрибутивов — архивов кода, которые могут быть распакованы в целевом окружении и установлены так, чтобы интерпретатор Python «увидел» распакованный код. При создании пакета программист создаёт в корневой директории будущего пакета файл setup.py в котором импортирует из модуля distutils функцию setup и вызывает её. Таким образом каждый пакет содержит в себе программу для управления собой!

Подробнее о том, как работает distutils, можно почитать в официальной документации к пакету, а мы сразу двинемся дальше. Дело в том, что пакет distutils появился довольно давно и сейчас сам по себе не очень удобен в использовании. Гораздо чаще используется надстройка над distutils, пакет setuptools.

Пакеты, собранные с помощью setuptools, уже умеют предоставлять metadata: описание, версию, и самое главное — собственные зависимости! Пакеты, которые не зависят ни от чего, кроме самого Python, настолько редки, что без setuptools — можно сказать, «жизни нет». Про этот пакет стоит знать и со временем нужно будет научиться его использовать (опять же, с помощью документации), но в рамках этого курса мы будем рассматривать более простой инструмент для создания пакетов и загрузки их в индекс — poetry, с которым мы познакомимся попозже.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *