1. Introducere

This document is intended to be both a tutorial and a reference guide. While it does not list all possible use cases, it should give a good overview of the principal functionality.

Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.3 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts.

O copie a acestei licențe este inclusă în secțiunea Licența GNU pentru Documentația liberă.

This license also applies to all code snippets in this document.

Python support was first introduced in QGIS 0.9. There are several ways to use Python in QGIS Desktop (covered in the following sections):

  • Issue commands in the Python console within QGIS

  • Create and use plugins

  • Automatically run Python code when QGIS starts

  • Create processing algorithms

  • Create functions for expressions in QGIS

  • Create custom applications based on the QGIS API

Python bindings are also available for QGIS Server, including Python plugins (see QGIS Server and Python) and Python bindings that can be used to embed QGIS Server into a Python application.

There is a complete QGIS C++ API reference that documents the classes from the QGIS libraries. The Pythonic QGIS API (pyqgis) is nearly identical to the C++ API.

Another good resource for learning how to perform common tasks is to download existing plugins from the plugin repository and examine their code.

1.1. Scripting in the Python Console

QGIS provides an integrated Python console for scripting. It can be opened from the Plugins ► Python Console menu:

../../_images/console.png

Fig. 1.4 Consola Python din QGIS

The screenshot above illustrates how to get the layer currently selected in the layer list, show its ID and optionally, if it is a vector layer, show the feature count. For interaction with the QGIS environment, there is an iface variable, which is an instance of QgisInterface. This interface allows access to the map canvas, menus, toolbars and other parts of the QGIS application.

For user convenience, the following statements are executed when the console is started (in the future it will be possible to set further initial commands)

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 Settings ► Keyboard shortcuts…)

1.2. Plugin-uri Python

The functionality of QGIS can be extended using plugins. Plugins can be written in Python. The main advantage over C++ plugins is simplicity of distribution (no compiling for each platform) and easier development.

Many plugins covering various functionality have been written since the introduction of Python support. The plugin installer allows users to easily fetch, upgrade and remove Python plugins. See the Python Plugins page for more information about plugins and plugin development.

Crearea de plugin-uri în Python este simplă, instrucțiuni detaliate găsindu-se în :ref: developing_plugins.

Notă

Python plugins are also available for QGIS server. See QGIS Server and Python for further details.

1.2.1. Processing Plugins

Processing Plugins can be used to process data. They are easier to develop, more specific and more lightweight than Python Plugins. Scrierea unui plugin Processing explains when the use of Processing algorithms is appropiate and how to develop them.

1.3. Running Python code when QGIS starts

There are different methods to run Python code every time QGIS starts.

  1. Creating a startup.py script

  2. Setting the PYQGIS_STARTUP environment variable to an existing Python file

  3. Specifying a startup script using the --code init_qgis.py parameter.

1.3.1. Fişierul startup.py

Every time QGIS starts, the user’s Python home directory and a list of system paths are searched for a file named startup.py. If that file exists, it is executed by the embedded Python interpreter.

The path in the user’s home directory usually is found under:

  • Linux: .local/share/QGIS/QGIS3

  • Windows: AppData\Roaming\QGIS\QGIS3

  • macOS: Library/Application Support/QGIS/QGIS3

The default system paths depend on the operating system. To find the paths that work for you, open the Python Console and run QStandardPaths.standardLocations(QStandardPaths.AppDataLocation) to see the list of default directories.

The startup.py script is executed immediately upon initializing python in QGIS, early on in the start of the application.

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.3.3. The --code parameter

You can provide custom code to execute as startup paramteter to QGIS. To do so, create a python file, for example qgis_init.py, to execute and start QGIS from the command line using qgis --code qgis_init.py.

Code provided via --code is executed late in the QGIS initialization phase, after the application components have been loaded.

1.3.4. Additional arguments for Python

To provide additional arguments for your --code script or for other python code that is executed, you can use the --py-args argument. Any argument coming after --py-args and before a -- arg (if present) will be passed to Python but ignored by the QGIS application itself.

In the following example, myfile.tif will be available via sys.argv in Python but will not be loaded by QGIS. Whereas otherfile.tif will be loaded by QGIS but is not present in sys.argv.

qgis --code qgis_init.py --py-args myfile.tif -- otherfile.tif

If you want access to every command line parameter from within Python, you can use QCoreApplication.arguments()

QgsApplication.instance().arguments()

1.4. Aplicații 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.

Aplicațiile personalizate PyQGIS, sau scrípturile independente, trebuie să fie configurate pentru a putea localizai resursele QGIS, cum ar fi informațiile despre proiecție și furnizorii pentru citirea straturilor vectoriale sau raster. Resursele QGIS sunt inițializate prin adăugarea a câtorva rânduri la începutul aplicației sau scríptului. Codul de inițializare QGIS este similar, atât pentru aplicațiile personalizate cât și pentru scrípturi. În continuare sunt prezentate câteva exemple.

Notă

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. Utilizarea PyQGIS în scrípturi de sine stătătoare

To start a standalone script, initialize the QGIS resources at the beginning of the script:

 1from qgis.core import *
 2
 3# Supply path to qgis install location
 4QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
 5
 6# Create a reference to the QgsApplication.  Setting the
 7# second argument to False disables the GUI.
 8qgs = QgsApplication([], False)
 9
10# Load providers
11qgs.initQgis()
12
13# Write your code here to load some layers, use processing
14# algorithms, etc.
15
16# Finally, exitQgis() is called to remove the
17# provider and layer registries from memory
18qgs.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 Scripting in the Python Console 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 initQgis() method.

qgs.initQgis()

With QGIS initialized, we are ready to write the rest of the script. Finally, we wrap up by calling exitQgis() to remove the data providers and layer registry from memory.

qgs.exitQgis()

1.4.2. Utilizarea PyQGIS în aplicații personalizate

The only difference between Utilizarea PyQGIS în scrípturi de sine stătătoare 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.

 1from qgis.core import *
 2
 3# Supply the path to the qgis install location
 4QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
 5
 6# Create a reference to the QgsApplication.
 7# Setting the second argument to True enables the GUI.  We need
 8# this since this is a custom application.
 9
10qgs = QgsApplication([], True)
11
12# load providers
13qgs.initQgis()
14
15# Write your code here to load some layers, use processing
16# algorithms, etc.
17
18# Finally, exitQgis() is called to remove the
19# provider and layer registries from memory
20qgs.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. Rularea Aplicațiilor Personalizate

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)

Aceste comenzi pot fi puse într-un script bootstrap, care se va ocupa de pornire. Atunci când livrați aplicații personalizate folosind PyQGIS, există, de obicei, două variante:

  • 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.

  • să împachetați QGIS împreună cu aplicația dumneavoastră. Livrarea aplicației poate fi mai dificilă deoarece pachetul va fi foarte mare, dar utilizatorul va fi salvat de povara de a descărca și instala software suplimentar.

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.