1. Introdução¶
Este documento pretende ser um tutorial e um guia de referência. Embora não liste todos os casos de uso possíveis, deve fornecer uma boa visão geral da funcionalidade principal.
O suporte ao Python foi introduzido pela primeira vez no QGIS 0.9. Existem várias maneiras de usar o Python no QGIS Desktop (abordado nas seções seguintes):
Emita comandos no console Python no QGIS
Crie e use complementos
Executar automaticamente o código Python quando o QGIS for iniciado
Create processing algorithms
Create functions for expressions in QGIS
Crie aplicativos personalizados com base na API QGIS
Python bindings are also available for QGIS Server, including Python plugins (see Servidor QGIS e Python) and Python bindings that can be used to embed QGIS Server into a Python application.
There is a complete QGIS API reference that documents the classes from the QGIS libraries. The Pythonic QGIS API (pyqgis) is nearly identical to the C++ API.
Um bom recurso para aprender como executar tarefas comuns é fazer o download de complementos existentes no repositório de complementos e examinar seu código.
1.1. Escrevendo Scripts no Terminal Python¶
O QGIS fornece um console Python integrado para scripts. Ele pode ser aberto no menu
A captura de tela acima ilustra como obter a camada atualmente selecionada na lista de camadas, mostrar seu ID e, opcionalmente, se for uma camada vetorial, mostrar o número de feições. Para interação com o ambiente QGIS, existe uma variável iface
, que é uma instância de QgisInterface
. Essa interface permite o acesso à tela do mapa, menus, barras de ferramentas e outras partes do aplicativo QGIS.
Para conveniência do usuário, as seguintes instruções são executadas quando o terminal é iniciado (no futuro, será possível definir mais comandos iniciais)
from qgis.core import *
import qgis.utils
For those which use the console often, it may be useful to set a shortcut for triggering the console (within
)1.2. Complementos Python¶
A funcionalidade do QGIS pode ser estendida usando complementos. Os complementos podem ser escritos em Python. A principal vantagem sobre os complementos C++ é a simplicidade de distribuição (sem compilação para cada plataforma) e o desenvolvimento mais fácil.
Muitos complementos que abrangem várias funcionalidades foram escritos desde a introdução do suporte ao Python. O instalador do complemento permite aos usuários buscar, atualizar e remover facilmente os complementos do Python. Veja a página Python Plugins para obter mais informações sobre complementos e desenvolvimento de complementos.
Criar complementos no Python é simples, veja development_plugins para instruções detalhadas.
Nota
Os complementos Python também estão disponíveis para o servidor QGIS. Veja Servidor QGIS e Python para mais detalhes.
1.3. Running Python code when QGIS starts¶
Existem dois métodos distintos de executar o código em Phyton toda vez que o QGIS é iniciado.
Creating a startup.py script
Setting the
PYQGIS_STARTUP
environment variable to an existing Python file
1.3.1. The startup.py
file¶
Every time QGIS starts, the user’s Python home directory
Linux:
.local/share/QGIS/QGIS3
Windows:
AppData\Roaming\QGIS\QGIS3
macOS:
Library/Application Support/QGIS/QGIS3
is searched for a file named startup.py
. If that file exists, it
is executed by the embedded Python interpreter.
Nota
The default path depends on the operating system. To find the
path that will work for you, open the Python Console and run
QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)
to see the list of default directories.
1.3.2. The PYQGIS_STARTUP environment variable¶
You can run Python code just before QGIS initialization completes by
setting the PYQGIS_STARTUP
environment variable to the path of an
existing Python file.
This code will run before QGIS initialization is complete. This method is very useful for cleaning sys.path, which may have undesireable paths, or for isolating/loading the initial environment without requiring a virtual environment, e.g. homebrew or MacPorts installs on Mac.
1.4. Aplicações Python¶
It is often handy to create scripts for automating processes.
With PyQGIS, this is perfectly possible — import
the qgis.core
module, initialize it and you are ready for the
processing.
Or you may want to create an interactive application that uses
GIS functionality — perform measurements, export a map as PDF, …
The qgis.gui
module provides various GUI
components, most notably the map canvas widget that can be
incorporated into the application with support for zooming, panning
and/or any further custom map tools.
PyQGIS custom applications or standalone scripts must be configured to locate the QGIS resources, such as projection information and providers for reading vector and raster layers. QGIS Resources are initialized by adding a few lines to the beginning of your application or script. The code to initialize QGIS for custom applications and standalone scripts is similar. Examples of each are provided below.
Nota
Do not use qgis.py
as a name for your script.
Python will not be able to import the bindings as the script’s
name will shadow them.
1.4.1. Using PyQGIS in standalone scripts¶
To start a standalone script, initialize the QGIS resources at the beginning of the script:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | from qgis.core import *
# Supply path to qgis install location
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
# Create a reference to the QgsApplication. Setting the
# second argument to False disables the GUI.
qgs = QgsApplication([], False)
# Load providers
qgs.initQgis()
# Write your code here to load some layers, use processing
# algorithms, etc.
# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()
|
First we import the qgis.core
module and configure
the prefix path. The prefix path is the location where QGIS is
installed on your system. It is configured in the script by calling
the setPrefixPath
method.
The second argument of
setPrefixPath
is set to True
, specifying that default paths are to be
used.
The QGIS install path varies by platform; the easiest way to find it
for your system is to use the Escrevendo Scripts no Terminal Python from within
QGIS and look at the output from running
QgsApplication.prefixPath()
.
After the prefix path is configured, we save a reference to
QgsApplication
in the variable qgs
. The second argument is set
to False
, specifying that we do not plan to use the GUI since
we are writing a standalone script. With QgsApplication
configured, we load the QGIS data providers and layer registry by
calling the qgs.initQgis()
method. With QGIS initialized, we are
ready to write the rest of the script. Finally, we wrap up by calling
qgs.exitQgis()
to remove the data providers and layer registry
from memory.
1.4.2. Using PyQGIS in custom applications¶
The only difference between Using PyQGIS in standalone scripts and a custom PyQGIS
application is the second argument when instantiating the QgsApplication
.
Pass True
instead of False
to indicate that we plan to
use a GUI.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | from qgis.core import *
# Supply the path to the qgis install location
QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
# Create a reference to the QgsApplication.
# Setting the second argument to True enables the GUI. We need
# this since this is a custom application.
qgs = QgsApplication([], True)
# load providers
qgs.initQgis()
# Write your code here to load some layers, use processing
# algorithms, etc.
# Finally, exitQgis() is called to remove the
# provider and layer registries from memory
qgs.exitQgis()
|
Now you can work with the QGIS API - load layers and do some processing or fire up a GUI with a map canvas. The possibilities are endless :-)
1.4.3. Executando aplicativos personalizados¶
You need to tell your system where to search for QGIS libraries and appropriate Python modules if they are not in a well-known location - otherwise Python will complain:
>>> import qgis.core
ImportError: No module named qgis.core
This can be fixed by setting the PYTHONPATH
environment variable. In
the following commands, <qgispath>
should be replaced with your actual
QGIS installation path:
on Linux: export PYTHONPATH=/<qgispath>/share/qgis/python
on Windows: set PYTHONPATH=c:\<qgispath>\python
on macOS: export PYTHONPATH=/<qgispath>/Contents/Resources/python
Now, the path to the PyQGIS modules is known, but they depend on
the qgis_core
and qgis_gui
libraries (the Python modules serve
only as wrappers). The path to these libraries may be unknown to the
operating system, and then you will get an import error again (the message
might vary depending on the system):
>>> import qgis.core
ImportError: libqgis_core.so.3.2.0: cannot open shared object file:
No such file or directory
Fix this by adding the directories where the QGIS libraries reside to the search path of the dynamic linker:
on Linux: export LD_LIBRARY_PATH=/<qgispath>/lib
on Windows: set PATH=C:\<qgispath>\bin;C:\<qgispath>\apps\<qgisrelease>\bin;%PATH% where
<qgisrelease>
should be replaced with the type of release you are targeting (eg,qgis-ltr
,qgis
,qgis-dev
)
These commands can be put into a bootstrap script that will take care of the startup. When deploying custom applications using PyQGIS, there are usually two possibilities:
require the user to install QGIS prior to installing your application. The application installer should look for default locations of QGIS libraries and allow the user to set the path if not found. This approach has the advantage of being simpler, however it requires the user to do more steps.
package QGIS together with your application. Releasing the application may be more challenging and the package will be larger, but the user will be saved from the burden of downloading and installing additional pieces of software.
The two deployment models can be mixed. You can provide a standalone applications on Windows and macOS, but for Linux leave the installation of GIS up to the user and his package manager.
1.5. Technical notes on PyQt and SIP¶
We’ve decided for Python as it’s one of the most favoured languages for scripting. PyQGIS bindings in QGIS 3 depend on SIP and PyQt5. The reason for using SIP instead of the more widely used SWIG is that the QGIS code depends on Qt libraries. Python bindings for Qt (PyQt) are done using SIP and this allows seamless integration of PyQGIS with PyQt.