Fontos
A fordítás közösségi munka, amihez itt tud csatlakozni. Ennek az oldalnak eddig 51.22%-a van lefordítva.
1. Bevezetés
Ez a dokumentum oktatóanyagként és referenciaként is szolgál. Bár nem sorolja fel az összes lehetséges felhasználási esetet, jó áttekintést nyújt a fő funkciókról.
A dokumentum másolására, terjesztésére és/vagy módosítására engedélyt adunk a GNU Free Documentation License 1.3-as verziójának vagy bármely későbbi, a Free Software Foundation által kiadott verziójának feltételei szerint; változatlan szakaszok, borítószöveg és hátlapszöveg nélkül.
A copy of the license is included in the section GNU Free Documentation License.
Ez a licenc a dokumentumban található összes kódrészletre is vonatkozik.
A Python támogatás először a QGIS 0.9-ben jelent meg. A Python többféleképpen is használható a QGIS-ben (ezeket a következő fejezetekben tárgyaljuk):
Parancsok kiadása a Python konzolban a QGIS-ben
Modulok létrehozása és használata
Python kód automatikus futtatása amikor a QGIS indul
Feldolgozás algoritmus létrehozása
Függvények készítése QGIS kifejezésekhez
Testre szabott alkalmazás létrehozása a QGIS API-val
A Python kötések a QGIS Szerverhez is elérhetők, beleértve a Python modulokat (lásd: QGIS Server and Python) és a Python kötéseket, amelyekkel a QGIS Szerver beágyazható egy Python alkalmazásba.
Létezik egy teljes QGIS C++ API referencia, amely dokumentálja a QGIS könyvtárak osztályait. A Python QGIS API (pyqgis) majdnem azonos a C++ API-val.
Egy másik jó forrás a gyakori feladatok elvégzéséhez a meglévő modulok letöltése a `modul tárház<https://plugins.qgis.org/>`_-ból, és a kódj megvizsgálása.
1.1. Szkript készítés a Python konzolban
A QGIS egy integrált Python konzolt biztosít szkriptek készítéséhez. Ez a menüből nyitható meg:

1.11. ábra QGIS Python konzol
A fenti képernyőkép bemutatja, hogyan lehet lekérni a réteglistából az aktuális réteget, megjeleníteni az azonosítóját, és opcionálisan, ha vektorrétegről van szó, az elemek számát. A QGIS környezettel való interakcióhoz létezik egy iface
változó, amely a QgisInterface
egy példánya. Ez az interfész lehetővé teszi a hozzáférést a térképvászonhoz, a menükhöz, az eszköztárakhoz és a QGIS alkalmazás egyéb részeihez.
A felhasználó kényeleme érdekében a következő utasítások hajtódnak végre a konzol indításakor (a jövőben további indítási parancsok beállítására is lehetőség lesz):
from qgis.core import *
import qgis.utils
Azoknak, akik gyakran használják a konzolt, hasznos lehet egy gyorsbillentyűt beállítani a konzol elindításához (a
menüpontban).1.2. Python modulok
A QGIS funkcionalitása modulokkal bővíthető. A modulok Pythonban írhatók. A C++ bővítményekkel szembeni fő előnyük az egyszerű terjesztés (nincs szükség minden platformra fordításra) és a könnyebb fejlesztés.
A Python támogatás bevezetése óta számos, különféle funkciókat lefedő modul született. A modul telepítője lehetővé teszi a felhasználók számára a Python bővítmények egyszerű letöltését, frissítését és eltávolítását. További információért a bővítményekről és fejlesztésükről lásd a Python modulok oldalt.
A modulok létrehozása Pythonban egyszerű, a részletes utasításokért lásd a Python modulok fejlesztése hivatkozást.
Megjegyzés
Python modulok a QGIS szerverhez is készíthetők. További részletekért lásd: QGIS Server and Python.
1.2.1. Feldolgozás modulok
A feldolgozás modulok adatfeldolgozásra használhatók. Fejlesztésük egyszerűbb, specifikusabbak és egyszerűbbek, mint a Python modulok,. A Egy feldolgozás modul írása elmagyarázza, hogy mikor helyénvaló a feldolgozás algoritmusok használata, és hogyan kell fejleszteni őket.
1.3. Python kód futtatása a QGIS indításakor
Különböző módszerek léteznek a Python kód futtatására minden alkalommal, amikor a QGIS elindul.
startup.py szkript létrehozása
PYQGIS_STARTUP
környezeti változó beállítása egy létező Python fájlraIndító szkript megadása a
--code init_qgis.py
paraméter használatával.
1.3.1. A startup.py
fájl
A QGIS minden indításakor a felhasználó Python könyvtárában és a rendszerútvonalak listájában keresi a startup.py
nevű fájlt. Ha a fájl létezik, a beágyazott Python interpreter végrehajtja.
Az elérési út a felhasználó saját könyvtárában a következő alatt található:
Linux:
.local/share/QGIS/QGIS3
Windows:
AppData\Roaming\QGIS\QGIS3
macOS:
Library/Application Support/QGIS/QGIS3
Az alapértelmezett rendszerútvonalak az operációs rendszertől függenek. A megfelelő elérési utak megkereséséhez nyissa meg a Python konzolt, és futtassa a QStandardPaths.standardLocations(QStandardPaths.AppDataLocation)
parancsot az alapértelmezett könyvtárak listájának megtekintéséhez.
A startup.py
szkript a QGIS-ben a Python inicializálása után azonnal végrehajtódik, az alkalmazás indulásának korai szakaszában.
1.3.2. A PYQGIS_STARTUP környezeti változó
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 parameter
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. Python Applications
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.
Megjegyzés
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:
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 Szkript készítés a Python konzolban 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. 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.
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. Running Custom Applications
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.