Установка pip для python и базовые команды

Первое знакомство

Модуль делает свою работу незаметно для пользователя. Например, если вы загрузили пакет, который был собран с помощью , а не , установка будет работать так, как вы этого ожидали: обычная установка . Для этого в пакет, собранный с помощью , добавляется небольшой загрузочный модульez_setup.py. Единственное предостережение здесь состоит в том, что пытается в фоновом режиме загрузить и установить необходимый пакет , для чего, естественно, необходима машина, подключенная к сети. Если уже установлен на машине, выполнять эту фоновую задачу нет необходимости; если же её необходимо выполнять вручную, большая часть прозрачности теряется. Однако на большинстве современных машин есть соединение с Интернет; для машин, не подключенных к сети, выполнение нескольких дополнительных операций не будет слишком обременительным.

Реальное преимущество не в том, что он делает то же самое, что и — даже несмотря на то, что этот модуль расширяет возможности и упрощает организацию сценария . Гораздо важнее, что модуль расширяет возможности по управлению пакетами. Довольно прозрачным образом вы можете находить, загружать и устанавливать зависимости; вы можете переключаться между несколькими версиями пакета, установленными на одну систему; вы можете объявлять требования к определенным версиям пакета; а также проводить обновление до последней версии используемого вами пакета с помощью простой команды. Едва ли не самым впечатляющим является тот факт, что вы можете использовать пакеты даже тех разработчиков, которые ничего не делали для реализации совместимости с .

Давайте рассмотрим эти возможности подробнее.

Creating The Scaffolding¶

The initial directory structure for funniest should look like this:

funniest
    funniest
        __init__.py
    setup.py

The top level directory is the root of our SCM repo, e.g. . The subdir, also called , is the actual Python module.

For starters we’ll put the function in , so it just contains:

def joke():
    return (u'Wenn ist das Nunst\u00fcck git und Slotermeyer? Ja! ... '
            u'Beiherhund das Oder die Flipperwaldt gersput.')

The main setup config file, , should contain a single call to , like so:

from setuptools import setup

setup(name='funniest',
      version='0.1',
      description='The funniest joke in the world',
      url='http://github.com/storborg/funniest',
      author='Flying Circus',
      author_email='flyingcircus@example.com',
      license='MIT',
      packages='funniest'],
      zip_safe=False)

Now we can install the package locally (for use on our system), with:

$ pip install .

We can also install the package with a symlink, so that changes to the source files will be immediately available to other users of the package on our system:

$ pip install -e .

Anywhere else in our system using the same Python, we can do this now:

Putting It All Together With The Full Windows Script¶

This project was build on a windows machine. To best understand how it all works
and the other options used when using setup.py let’s just look at the
.bat file I use to build the package and upload it to pypi:

set HOME=C:\Users\Owner\
cd C:\eclipse\workspace\HG_AN_EXAMPLE_PYPI_PROJECT
C:\Python24\python.exe setup.py bdist_egg upload --identity="Andrew Carter" --sign --quiet
C:\Python25\python.exe setup.py bdist_egg upload --identity="Andrew Carter" --sign --quiet
C:\Python26\python.exe setup.py bdist_egg upload --identity="Andrew Carter" --sign --quiet
C:\Python24\python.exe setup.py bdist_wininst --target-version=2.4 register upload --identity="Andrew Carter" --sign --quiet
C:\Python25\python.exe setup.py bdist_wininst --target-version=2.5 register upload --identity="Andrew Carter" --sign --quiet
C:\Python26\python.exe setup.py bdist_wininst --target-version=2.6 register upload --identity="Andrew Carter" --sign --quiet
C:\Python26\python.exe setup.py sdist upload --identity="Andrew Carter" --sign
pause

For linux, it would be pretty much the same commands, just changing around
the directories to point to the correct python versions.

Note

I use the set HOME=C:\Users\Owner\ instead of setting an environ variable on windows

Создание пакетов, более осведомленных о setuptools

Я могу позволить пользователям устанавливать утилиты Gnosis, даже не зная каталога для загрузки. Это почти работает, просто потому, что утилиты Gnosis занесены в листинг на Python Cheeseshop. К несчастью, не зная о , я допустил небольшую неточность при создании записи для утилит Gnosis на python.org по адресу http://www.python.org/pypi/Gnosis%20Utilities/1.2.1. Если быть более точным, нумерация архивов выполнялась по шаблону . (Утилиты также архивируются в архивы .zip и .tar.bz2, а несколько последних версий — как установочные программы win32.exe, и одинаково хорошо работает со всеми). Однако, название проекта на Cheeseshop пишется несколько иначе, как «Gnosis Utilities». Итак, небольшое административное изменение версии на Cheeseshop создает http://www.python.org/pypi/Gnosis_Utils/1.2.1-a как версию, вышедшую после официального выпуска. В самих архивах ничего не изменилось, лишь произошли незначительные изменения в метаданных Cheeseshop

С помощью небольших настроек мы можем ещё больше упростить установку (обратите внимание, что для тестирования я запустил промежуточную команду , удаляющую установленный пакет)

Листинг 9. Простое добавление осведомленности о setuptools
% easy_install Gnosis_Utils
Searching for Gnosis-Utils
Reading http://www.python.org/pypi/Gnosis_Utils/
Reading http://www.gnosis.cx/download/Gnosis_Utils.ANNOUNCE
Reading http://gnosis.cx/download/Gnosis_Utils.More/
Best match: Gnosis-Utils 1.2.1
Downloading 

Я опускаю завершение процесса, так как оно аналогично тому, что мы уже видели. Единственное изменение состоит в том, что выполняет поиск на Cheeseshop (другими словами, на ) метаданных пакета, соответствующего указанному имени, и использует их для поиска фактической ссылки для загрузки. В рассматриваемом примере в файле .ANNOUNCE не содержится ничего полезного, однако также будет просматривать и другие указанные ссылки, по которым может находиться каталог загрузки.

Установка «неосведомленных» пакетов

Пакет уже «знает» о , а что будет, если вы желаете установить пакет, автор которого не предусматривал использование ? Например, до написания этой статьи я никогда не использовал с моими утилитами Gnosis. Итак, давайте попробуем установить пакет, зная только адрес HTTP (или FTP, SVN, CVS), где он хранится ( знает все эти протоколы). На моем сайте доступны для загрузки архивы различных версий утилит Gnosis, имена которым даны обычным образом:

Листинг 5. Установка пакета, не знающего о setuptools
% easy_install -f http://gnosis.cx/download/Gnosis_Utils.More/ Gnosis_Utils
Searching for Gnosis-Utils
Reading http://gnosis.cx/download/Gnosis_Utils.More/
Best match: Gnosis-Utils 1.2.1
Downloading http://gnosis.cx/download/Gnosis_Utils.More/
  Gnosis_Utils-1.2.1.zip
Processing Gnosis_Utils-1.2.1.zip
Running Gnosis_Utils-1.2.1/setup.py -q bdist_egg --dist-dir
  /tmp/easy_install-CCrXEs/Gnosis_Utils-1.2.1/egg-dist-tmp-Sh4DW1
zip_safe flag not set; analyzing archive contents...
gnosis.__init__: module references __file__
gnosis.magic.__init__: module references __file__
gnosis.xml.objectify.doc.__init__: module references __file__
gnosis.xml.pickle.doc.__init__: module references __file__
gnosis.xml.pickle.test.test_zdump: module references __file__
Adding Gnosis-Utils 1.2.1 to easy-install.pth file

Installed /sw/lib/python2.4/site-packages/Gnosis_Utils-1.2.1-py2.4.egg
Processing dependencies for Gnosis-Utils

К счастью для нас, сценарий со всем разобрался. Он просматривает каталог загрузки, находит последнюю версию, распаковывает архив и запаковывает его снова как «egg», который после этого устанавливается. Теперь импорт отлично работает в сценарии. Однако допустим, что вам нужно проверить в сценарии определенную более раннюю версию утилит Gnosis? Это достаточно просто:

Листинг 6. Установка определенной версии «неосведомленного» пакета
% easy_install -f http://gnosis.cx/download/Gnosis_Utils.More/
  "Gnosis_Utils==1.2.0"
Searching for Gnosis-Utils==1.2.0
Reading http://gnosis.cx/download/Gnosis_Utils.More/
Best match: Gnosis-Utils 1.2.0
Downloading http://gnosis.cx/download/Gnosis_Utils.More/
  Gnosis_Utils-1.2.0.zip

Removing Gnosis-Utils 1.2.1 from easy-install.pth file
Adding Gnosis-Utils 1.2.0 to easy-install.pth file

Installed /sw/lib/python2.4/site-packages/Gnosis_Utils-1.2.0-py2.4.egg
Processing dependencies for Gnosis-Utils==1.2.0

Сейчас фактически установлено две версии утилит Gnosis, активной версией является 1.2.0. Переключение с активной версии на версию 1.2.1 также выполняется достаточно просто:

Листинг 7. Изменение «активной» версии для системы
% easy_install "Gnosis_Utils==1.2.1"
Searching for Gnosis-Utils==1.2.1
Best match: Gnosis-Utils 1.2.1
Processing Gnosis_Utils-1.2.1-py2.4.egg
Removing Gnosis-Utils 1.2.0 from easy-install.pth file
Adding Gnosis-Utils 1.2.1 to easy-install.pth file

Using /sw/lib/python2.4/site-packages/Gnosis_Utils-1.2.1-py2.4.egg
Processing dependencies for Gnosis-Utils==1.2.1

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

Листинг 8. Использование версии пакета в сценарии
from pkg_resources import require
require("Gnosis_Utils==1.2.0")

При указании этого требования модуль при запуске оператора добавит указанную версию (или последнюю, если указано сравнение «больше чем»).

1.0¶

17 Aug 2013

  • Issue #60: On Windows, Setuptools supports deferring to another launcher,
    such as Vinay Sajip’s pylauncher
    (included with Python 3.3) to launch console and GUI scripts and not install
    its own launcher executables. This experimental functionality is currently
    only enabled if the environment variable is set to
    “natural”. In the future, this behavior may become default, but only after
    it has matured and seen substantial adoption. The
    also accepts “executable” to force the default behavior of creating launcher
    executables.
  • Issue #63: Bootstrap script (ez_setup.py) now prefers Powershell, curl, or
    wget for retrieving the Setuptools tarball for improved security of the
    install. The script will still fall back to a simple on
    platforms that do not have these tools.
  • Issue #65: Deprecated the functionality.
  • Issue #52: In , handle a tunnelled (proxied)
    connection.

Publishing On PyPI¶

The script is also our main entrypoint to register the package name on PyPI and upload source distributions.

To “register” the package (this will reserve the name, upload package metadata, and create the pypi.python.org webpage):

$ python setup.py register

If you haven’t published things on PyPI before, you’ll need to create an account by following the steps provided at this point.

At this point you can view the (very minimal) page on PyPI describing funniest:

Although users can follow the URL link to find our git repository, we’ll probably want to upload a source distribution so that the package can be installed without cloning the repository. This will also enable automated installation and dependency resolution tools to install our package.

First create a source distribution with:

$ python setup.py sdist

This will create inside our top-level directory. If you like, copy that file to another host and try unpacking it and install it, just to verify that it works for you.

That file can then be uploaded to PyPI with:

$ python setup.py sdist upload

You can combine all of these steps, to update metadata and publish a new build in a single step:

$ python setup.py register sdist upload

For a detailed list of all available setup.py commands, do:

Начальная загрузка

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

Первым шагом процесса является простая загрузка небольшого сценария :

Листинг 1. Скачивание загрузочного сценария
% wget -q http://peak.telecommunity.com/dist/ez_setup.py

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

Листинг 2. Начальная загрузка setuptools
% python ez_setup.py
Downloading http://cheeseshop.python.org/packages/2.4/s/
  setuptools/setuptools-0.6b1-py2.4.egg#md5=b79a8a403e4502fbb85ee3f1941735cb
Processing setuptools-0.6b1-py2.4.egg
creating /sw/lib/python2.4/site-packages/setuptools-0.6b1-py2.4.egg
Extracting setuptools-0.6b1-py2.4.egg to /sw/lib/python2.4/site-packages
Removing setuptools 0.6a11 from easy-install.pth file
Adding setuptools 0.6b1 to easy-install.pth file
Installing easy_install script to /sw/bin
Installing easy_install-2.4 script to /sw/bin

Installed /sw/lib/python2.4/site-packages/setuptools-0.6b1-py2.4.egg
Processing dependencies for setuptools

Все готово. Это всё, что вам нужно, чтобы быть уверенным, что на вашей системе установлен модуль .

Implementation strategy

To ensure there is no need for network access when installing Python or
creating virtual environments, the ensurepip module will, as an
implementation detail, include a complete private copy of pip and its
dependencies which will be used to extract pip and install it into the target
environment. It is important to stress that this private copy of pip is
only an implementation detail and it should not be relied on or
assumed to exist beyond the public capabilities exposed through the
ensurepip module (and indirectly through venv).

There is not yet a reference ensurepip implementation. The existing
get-pip.py bootstrap script demonstrates an earlier variation of the
general concept, but the standard library version would take advantage of
the improved distribution capabilities offered by the CPython installers
to include private copies of pip and setuptools as wheel files
(rather than as embedded base64 encoded data), and would not try to
contact PyPI (instead installing directly from the private wheel files).

Rather than including separate code to handle the bootstrapping, the
ensurepip module will manipulate sys.path appropriately to allow
the wheel files to be used to install themselves, either into the current
Python installation or into a virtual environment (as determined by the
options passed to the bootstrap command).

It is proposed that the implementation be carried out in five separate
steps (all steps after the first two are independent of each other and
can be carried out in any order):

0.6¶

09 Aug 2009

setuptools

  • Packages required at build time where not fully present at install time.
    This closes Distribute #12.
  • Protected against failures in tarfile extraction. This closes Distribute #10.
  • Made Jython api_tests.txt doctest compatible. This closes Distribute #7.
  • sandbox.py replaced builtin type file with builtin function open. This
    closes Distribute #6.
  • Immediately close all file handles. This closes Distribute #3.
  • Added compatibility with Subversion 1.6. This references Distribute #1.

pkg_resources

  • Avoid a call to /usr/bin/sw_vers on OSX and use the official platform API
    instead. Based on a patch from ronaldoussoren. This closes issue #5.
  • Fixed a SandboxViolation for mkdir that could occur in certain cases.
    This closes Distribute #13.
  • Allow to find_on_path on systems with tight permissions to fail gracefully.
    This closes Distribute #9.
  • Corrected inconsistency between documentation and code of add_entry.
    This closes Distribute #8.
  • Immediately close all file handles. This closes Distribute #3.

Intermezzo: .pypirc file and gpg¶

In order to interact with pypi, you first need to setup an account. Go to
http://pypi.python.org/pypi and click on Register.

Now, once registered, when you run setup.py commands that interact with
pypi you’ll have to enter your username and password each time.

To get around this, place a .pypirc file in your $HOME directory on
linux. On windows, an you’ll need to set a HOME environ var to point to
the directory where this file lives.

The structure of a .pypirc file is pretty simple:

servers = pypi

username:your_awesome_username
password:your_awesome_password

Note

There’s probably away around having your plain text password in this file,
but I don’t know of the solution and haven’t looked into it.

skbuild.cmaker module¶

This module provides an interface for invoking CMake executable.

class (cmake_executable=’cmake’)

Bases:

Interface to CMake executable.

static ()

This function tries to catch files that are meant to be installed
outside the project root before they are actually installed.

Indeed, we can not wait for the manifest, so we try to extract the
information (install destination) from the CMake build files
found in .

It raises if it found install destination outside of
.

(clargs=(), generator_name=None, skip_generator_test=False, cmake_source_dir=’.’, cmake_install_dir=», languages=’C’, ‘CXX’, cleanup=True)

Calls cmake to generate the Makefile/VS Solution/XCode project.

clargs: tuple

List of command line arguments to pass to cmake executable.

generator_name: string

The string representing the CMake generator to use.
If None, uses defaults for your platform.

skip_generator_test: bool

If set to True and if a generator name is specified (either as a keyword
argument or as clargs using -G <generator_name>), the generator test
is skipped.

cmake_source_dir: string

Path to source tree containing a

cmake_install_dir: string

Relative directory to append
to .

languages: tuple

List of languages required to configure the project and expected to
be supported by the compiler. The language identifier that can be specified
in the list corresponds to the one recognized by CMake.

cleanup: bool

If True, cleans up temporary folder used to test
generators. Set to False for debugging to see CMake’s
output files.

Return a mapping of the environment associated with the
selected .

Mapping of the environment can also be later retrieved using .

()

If any, return a mapping of environment associated with the cached generator.

()

Reads and returns the cached generator from the :.
Returns None if not found.

static (python_version)

Get include directory associated with the current python
interpreter.

static (python_version)

Get path to the python library associated with the current python
interpreter.

static ()

Get version associated with the current python interpreter.

()

Returns a list of file paths to install via setuptools that is
compatible with the data_files keyword argument.

(clargs=(), config=’Release’, source_dir=’.’, env=None)

Calls the system-specific make program to compile code.

(cmake_executable=’cmake’)

Runs CMake and extracts associated version information.
Raises if it failed to execute CMake.

(cmake_args, arg_name, arg_value=None)

Return True if is found
in . If is None, return True only if
is found in the list.

Setting up setup.py¶

All the features of what can go into a setup.py file is beyond the
scope of this simple tutorial. I’ll just focus on a very basic and common
format needed to get this project onto pypi.

The contents of setup.py is just pure python:

import os
from setuptools import setup

# Utility function to read the README file.
# Used for the long_description.  It's nice, because now 1) we have a top level
# README file and 2) it's easier to type in the README file than to put a raw
# string in below ...
def read(fname):
    return open(os.path.join(os.path.dirname(__file__), fname)).read()

setup(
    name = "an_example_pypi_project",
    version = "0.0.4",
    author = "Andrew Carter",
    author_email = "andrewjcarter@gmail.com",
    description = ("An demonstration of how to create, document, and publish "
                                   "to the cheese shop a5 pypi.org."),
    license = "BSD",
    keywords = "example documentation tutorial",
    url = "http://packages.python.org/an_example_pypi_project",
    packages='an_example_pypi_project', 'tests'],
    long_description=read('README'),
    classifiers=
        "Development Status :: 3 - Alpha",
        "Topic :: Utilities",
        "License :: OSI Approved :: BSD License",
    ],
)

Directory Structure

The directory structure, so far, should look like this:

some_root_dir/
|-- README
|-- setup.py
|-- an_example_pypi_project
|   |-- __init__.py
|   |-- useful_1.py
|   |-- useful_2.py
|-- tests
|-- |-- __init__.py
|-- |-- runall.py
|-- |-- test0.py

README

A nice idea stolen from http://pypi.python.org/pypi/Sphinx-PyPI-upload is to
include a README text file which your code. This would be visible when someone,
say, cloned your repo.

Using the simple read function, it is easy to include this in the
long_description keyword arg for the setuptools.setup() function.

Заключение

На самом деле я только приоткрыл возможности настройки дистрибутивов, осведомленных о существовании . Например, если у вас есть дистрибутив (или в предпочтительном формате egg, или в архиве другого типа), вы можете автоматически загрузить метаданные в Cheeseshop с помощью одной команды. Безусловно, полный сценарий должен содержать те же подробные метаданные, которые содержатся в старом сценарии ; я пропустил это для простоты изложения, однако названия параметров совместимы с .

Для того, чтобы достичь полной совместимости с огромными возможностями , нужно немного, однако это действительно облегчает и поддержание собственных и установку сторонних пакетов по сравнению с . И если всё, что вас заботит — это установка пакетов, в этом введении содержится всё, что вам нужно знать; сложности начинаются только с описанием собственных пакетов, но эти сложности значительно меньше, чем необходимые для того, чтобы разобраться с .

Похожие темы

  • Оригинал статьи Charming Python: Hatch Python eggs with setuptools
  • На сайте Python Cheese Shop можно загрузить последнюю версию .
  • Ознакомьтесь с предыдущими колонками Давида по PEAK: «The Python Enterprise Application Kit» (developerWorks, май 2004 г.) и «Масштабирование нового PEAK» (developerWorks, сентябрь 2005 г.)
  • На домашней странице PEAK можно найти общее введение к библиотеке.
  • Полное руководство по имеется в Интернете.
  • Gnosis Utilities комплект полезных библиотек Python Дэвида Мертца, можно скачать с Cheese Shop.
  • В зоне Linux сайта developerWorks вы найдете ресурсы для разработчиков Linux.
  • Используйте в своем следующем проекте разработки для Linux ознакомительные версии программного обеспечения IBM, которые можно скачать непосредственно с сайта developerWorks.
Добавить комментарий

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

Adblock
detector