Today I wanted to hack together a standalone script using PyQGIS, the QGIS Python bindings, to write a small prototype. I hadn’t written such a standalone script yet, but it seemed to be low hanging fruit. Turns out, it isn’t really straight forward on Ubuntu. Here I am going to show you how it worked for me.
Reading the relevant docs in the PyQGIS Developer Cookbook, I assumed it would be a quick copy/paste job to setup the QGIS application context inside the script. But the devil is in the detail. The docs seem to assume you installed QGIS by compiling master or something similar, controlling the place where QGIS’ resources are installed. But I am using the pre-built packages from qgis.org package repo.
Here you see the most basic form of a PyQGIS script, according to the docs. It does only initialize the QGIS Application instance, nothing more. But before we can run it, we need to make sure that Python finds the imported QGIS modules.
from qgis.core import QgsApplication # Supply path to qgis install location QgsApplication.setPrefixPath("/usr/bin/qgis", True) # Create a reference to the QgsApplication. Setting the # second argument to False disables the GUI. qgs = QgsApplication(, False) # Load providers qgs.initQgis() # Put your pyqgis code here: print("Success!") # Finally, exitQgis() is called to remove the # provider and layer registries from memory qgs.exitQgis()
The docs tell us to use something like this on Linux to tell Python where to find the QGIS Python modules:
But where is this
I didn’t find any docs or other help online, so I used
dpkg-query -L <package_name> to locate files that have been installed with the
qgis package. Turns out, QGIS on Ubuntu from qgis.org repo consists of a whole lot of different packages, and also properly uses the systems own package manager to install more Python dependencies. The PyQGIS stuff is also packaged to fit into the scheme and therefore provides an independent
python3-qgis package, which drops the python modules in
Now, when I set the PYTHONPATH using
and run the script from above using
I don’t get any more
ModuleNotFoundError: No module named 'qgis'.
Fortunately, I don’t get any errors from missing linked libraries as anticipated in the docs.