dockerdebianqgispyqgis

Segmentation Fault after creating PyQGIS standalone application the second time even after exitQgis() - Debian


I am trying to create several .qgs project files to be served at a later time by an instance of qgis Server. To this end I need to start a new PyQGIS application several times upon request. The application runs smoothly the first time it is called, but if I try to run it a second time I get a Segmentation Fault error.

Here is an example code that triggers the problem:

from qgis.core import QgsApplication
import os

os.environ["QT_QPA_PLATFORM"] = "offscreen"

for i in range(2):
    print(f'Iteration number {i}')

    print('\tSet prefix path')
    QgsApplication.setPrefixPath('/usr', False)    
    
    print('\tInstantiating application')
    qgs = QgsApplication([], False)
    
    print('\tInitializing application')
    qgs.initQgis()
    
    print('\tExiting')
    qgs.exitQgis()

When executed, I get this output:

Iteration number 0
        Set prefix path
        Instantiating application
QStandardPaths: XDG_RUNTIME_DIR not set, defaulting to '/tmp/runtime-root'
        Initializing application
        Exiting
Iteration number 1
        Set prefix path
        Instantiating application
        Initializing application
Segmentation fault

Something similar happens if I enclose the content of the loop inside a function and call it multiple times. In this case the segmentation fault happens upon calling qgs.exitQgis() the second time (and any vector or raster layers added before that would be invalid).

Maybe the problem is that for some reason qgs.exitQgis() is not really cleaning up before exit?

The code is running on a Python:3.9 docker container that comes with Debian Bullseye. Qgis has been installed following the instruction from the QGIS docs: https://qgis.org/en/site/forusers/alldownloads.html#debian-ubuntu. QGIS version is QGIS 3.22.3-Białowieża 'Białowieża'.

To prevent an import error when loading qgis.core I had to set the environment variable PYTHONPATH = /usr/lib/python3/dist-packages/.


Solution

  • It seems like the problem was fixed in QGIS ver. 3.24 Tisler. Now qgs.exitQgis() can be called in a loop without triggering a segmentation fault.