skip to Main Content

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

2

Answers


  1. Chosen as BEST ANSWER

    UPDATE: Following a suggestion of one comment found on this post:
    https://gis.stackexchange.com/questions/250933/using-exitqgis-in-pyqgis,
    I substituted qgs.exitQgis() with qgs.exit() and now the app can be instantiated again any number of times without crashing.

    It is still not clear what causes the segmentation fault, but at least I found this workaround.


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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search