Instalando módulos Python

As a popular open source development project, Python has an active supporting community of contributors and users that also make their software available for other Python developers to use under open-source license terms.

Isso permite aos usuários Python compartilhar e colaborar efetivamente, se beneficiando das soluções que outros já tenham criado para os problemas mais comuns (em alguns casos até mesmo os raros), bem como potencialmente contribuindo com suas próprias soluções para o conjunto de soluções comuns.

Este guia cobre a parte do processo de instalação. Para um guia sobre criar e compartilhar seus próprios projetos Python, confira o Guia de Usuário para Empacotamento de Python.

Nota

Para corporações e outros usuários institucionais, esteja ciente que muitas organizações têm suas próprias políticas em relação ao uso e contribuição para o software de código aberto. Por favor, leve em conta essas políticas ao usar as ferramentas de distribuição e instalação fornecidas com o Python.

Termos chave

  • pip is the preferred installer program. It is included by default with the Python binary installers.

  • Um ambiente virtual é um ambiente Python semi-isolado que permite que pacotes sejam instalados para uso por uma aplicação específica, em vez de serem instaladas em todo o sistema.

  • venv is the standard tool for creating virtual environments. It defaults to installing pip into all created virtual environments.

  • virtualenv is a third-party alternative (and predecessor) to venv.

  • The Python Package Index (PyPI) is a public repository of open source licensed packages made available for use by other Python users.

  • The Python Packaging Authority is the group of developers and documentation authors responsible for the maintenance and evolution of the standard packaging tools and the associated metadata and file format standards. They maintain a variety of tools, documentation, and issue trackers on GitHub.

Alterado na versão 3.5: O uso de venv agora é recomendado para a criação de ambientes virtuais.

Uso básico

As ferramentas de empacotamento padrão são todas projetadas para serem usadas na linha de comando.

The following command will install the latest version of a module and its dependencies from PyPI:

python -m pip install AlgumPacote

Nota

Para usuários POSIX (incluindo usuários macOS e Linux), os exemplos neste guia presumem o uso de um ambiente virtual.

Para usuários do Windows, os exemplos neste guia presumem que a opção de ajustar a variável de ambiente PATH do sistema foi selecionada durante a instalação do Python.

Também é possível especificar uma versão exata ou mínima diretamente na linha de comando. Ao usar operadores de comparação como >, < ou algum outro caractere especial que é interpretado pelo shell, o nome do pacote e a versão devem ser colocados entre aspas duplas:

python -m pip install AlgumPacote==1.0.4    # versão específica
python -m pip install "AlgumPacote>=1.0.4"  # versão mínima

Normalmente, se um módulo adequado já estiver instalado, tentar instalá-lo novamente não terá efeito. A atualização de módulos existentes deve ser solicitada explicitamente:

python -m pip install --upgrade AlgumPacote

More information and resources regarding pip and its capabilities can be found in the Python Packaging User Guide.

A criação de ambientes virtuais é feita através do módulo venv. A instalação de pacotes em um ambiente virtual ativo usa os comandos mostrados acima.

Como eu …?

Estas são respostas rápidas ou links para algumas tarefas comuns.

… instalo pacotes apenas para o usuário atual?

Passar a opção --user para python -m pip install irá instalar um pacote apenas para o usuário atual, ao invés de para todos os usuários do sistema.

… instalo pacotes científicos do Python?

A number of scientific Python packages have complex binary dependencies, and aren’t currently easy to install using pip directly. It will often be easier for users to install these packages by other means rather than attempting to install them with pip.

… trabalho com várias versões do Python instaladas em paralelo?

On Linux, macOS, and other POSIX systems, use the versioned Python commands in combination with the -m switch to run the appropriate copy of pip:

python3    -m pip install SomePackage  # default Python 3
python3.14 -m pip install SomePackage  # specifically Python 3.14

Appropriately versioned pip commands may also be available.

On Windows, use the py Python launcher in combination with the -m switch:

py -3    -m pip install SomePackage  # default Python 3
py -3.14 -m pip install SomePackage  # specifically Python 3.14

Problemas comuns de instalação

Instalando no sistema Python no Linux

On Linux systems, a Python installation will typically be included as part of the distribution. Installing into this Python installation requires root access to the system, and may interfere with the operation of the system package manager and other components of the system if a component is unexpectedly upgraded using pip.

On such systems, it is often better to use a virtual environment or a per-user installation when installing packages with pip.

Pip não instalado

It is possible that pip does not get installed by default. One potential fix is:

python -m ensurepip --default-pip

There are also additional resources for installing pip.

Instalando extensões binárias

Python once relied heavily on source-based distribution, with end users being expected to compile extension modules from source as part of the installation process.

With the introduction of the binary wheel format, and the ability to publish wheels through PyPI, this problem is diminishing, as users are more regularly able to install pre-built extensions rather than needing to build them themselves.

Some of the solutions for installing scientific software that are not yet available as pre-built wheel files may also help with obtaining other binary extensions without needing to build them locally.