Ubuntu logo

Developer

Empacotamento de aplicativos e módulos Python

Our packaging follows Debian’s Python policy. We will use the python-markdown package as an example, which can be downloaded from PyPI. You can look at its packaging at its Subversion repository.

Existem dois tipos de pacotes Python — módulos e aplicativos.

At the time of writing, Ubuntu has two incompatible versions of Python — 2.x and 3.x. /usr/bin/python is a symbolic link to a default Python 2.x version, and /usr/bin/python3 — to a default Python 3.x version. Python modules should be built against all supported Python versions.

Se você vai empacotar um novo módulo Python, a ferramenta “py2dsc” pode lhe ser útil (disponível no pacote python-stdeb).

debian/control

Python 2.x and 3.x versions of the package should be in separate binary packages. Names should have python{,3}-modulename format (like: python3-dbus.mainloop.qt). Here, we will use python-markdown and python3-markdown for module packages and python-markdown-doc for the documentation package.

Coisas no debian/control que são específicas para um pacote Python:

  • A seção de pacotes de módulos deve ser “python”, e “doc” para o pacote de documentação. Para um aplicativo, um único pacote binário é o suficiente.

  • We should add build dependencies on python-all (>= 2.6.6-3~) and python3-all (>= 3.1.2-7~) to make sure Python helpers are available (see the next section for details).

  • É recomendado adicionar os campos “X-Python-Version” e “X-Python3-Version” — consulte a seção “Especificando versões suportadas” para mais detalhes. Por exemplo:

    X-Python-Version: >= 2.6
    X-Python3-Version: >= 3.1

    Se o seu pacote funciona somente como o Python 2.x ou 3.x, compile como dependente de apenas um pacote (“-all”) e utilize apenas um campo de versão (“-Version”).

  • Os pacotes de módulos devem ter variáveis de substituição “{python:Depends}” e “{python3:Depends}” (respectivamente) em suas listas de dependências.

debian/rules

The recommended helpers for python modules are dh_python2 and dh_python3. Unfortunately, debhelper doesn’t yet build Python 3.x packages automatically (see bug 597105 in Debian BTS), so we’ll need to do that manually in override sections (skip this if your package doesn’t support Python 3.x).

Aqui está nosso arquivo debian/rules (com anotações):

# These commands build the list of supported Python 3 versions
# The last version should be just “python3” so that the scripts
# get a correct shebang.
# Use just “PYTHON3 := $(shell py3versions -r)” if your package
# doesn’t contain scripts
PY3REQUESTED := $(shell py3versions -r)
PY3DEFAULT := $(shell py3versions -d)
PYTHON3 := $(filter-out $(PY3DEFAULT),$(PY3REQUESTED)) python3

%:
    # Adding the required helpers
    dh $@ --with python2,python3

override_dh_auto_clean:
    dh_auto_clean
    rm -rf build/

override_dh_auto_build:
    # Build for each Python 3 version
    set -ex; for python in $(PYTHON3); do \
        $$python setup.py build; \
    done
    dh_auto_build

override_dh_auto_install:
    # The same for install; note the --install-layout=deb option
    set -ex; for python in $(PYTHON3); do \
        $$python setup.py install --install-layout=deb --root=debian/tmp; \
    done
    dh_auto_install

É de boa prática executar testes durante a compilação, se eles forem enviados pelo upstream. Normalmente, testes podem ser invocados usando “setup.py test” ou “setup.py check”.

debian/*.install

Python 2.x modules are installed into /usr/share/pyshared/ directory, and symbolic links are created in /usr/lib/python2.x/dist-packages/ for every interpreter version, while Python 3.x ones are all installed into /usr/lib/python3/dist-packages/.

If your package is an application and has private Python modules, they should be installed in /usr/share/module, or /usr/lib/module if the modules are architecture-dependent (e.g. extensions) (see “Programs Shipping Private Modules” section of the Policy).

Então, o nosso arquivo “python-markdown.install” irá parecer assim (teremos que instalar o executável “markdown_py”):

usr/lib/python2.*/
usr/bin/

e python3-markdown.install terá uma linha:

usr/lib/python3/

O pacote -doc

A ferramenta mais usada para compilar documentação Python é o Sphinx. Para adicionar documentação Sphinx ao seu pacote (usando o ajudante “dh_sphinxdoc”), você deve:

  • Adicione uma dependência de compilação em “python-sphinx” ou “python3-sphinx” (dependendo da versão do Python que você queria usar);
  • Adicione “sphinxdoc” à linha “dh –with”;
  • Execute “setup.py build_sphinx” em “override_dh_auto_build” (às vezes não necessário);
  • Adicionar {sphinxdoc:Depends} para lista de dependências do seu pacote -doc;
  • Adicione o caminho do diretório da documentação compilada (normalmente “build/sphinx/html”) no seu arquivo ”.docs”.

No nosso caso, a documentação é automaticamente compilada no diretório “build/docs/” quando executamos “setup.py build”, então podemos simplesmente colocá-la no arquivo “python-markdown-doc.docs”:

build/docs/

Pelo fato de que docs também contém arquivos fonte ”.txt”, nós também diremos ao “dh_compress” para não comprimi-los, adicionando isto ao “debian/rules”:

override_dh_compress:
    dh_compress -X.txt

Verificando por erros de empacotamento

Along with lintian, there is a special tool for checking Python packages — lintian4py. It is available in the lintian4python package. For example, these two commands invoke both versions of lintian and check source and binary packages:

lintian -EI --pedantic *.dsc *.deb
lintian4py -EI --pedantic *.dsc *.deb

Aqui, a opção -EI é usada para habilitar as etiquetas informativas e experimentais.

Veja também