PyQGIS – Terminate Standalone Python Script in QGIS Properly

gdalogrprint-composerpyqgisstandalone

I want to write Python standalone QGIS script to layout export and my code is as follows:

import os
from qgis.core import (
    QgsVectorLayer,QgsProject, QgsWkbTypes,QgsVectorLayerExporter,QgsCoordinateReferenceSystem,QgsProviderRegistry,  QgsGeometry,
    QgsMapSettings,
    QgsPrintLayout,
    QgsMapSettings,
    QgsMapRendererParallelJob,
    QgsLayoutItemLabel,
    QgsLayoutItemLegend,
    QgsLayoutItemMap,
    QgsLayoutItemPolygon,
    QgsLayoutItemScaleBar,
    QgsLayoutExporter,
    QgsLayoutItem,
    QgsLayoutPoint,
    QgsLayoutSize,    
    QgsUnitTypes,    
    QgsFillSymbol,
    QgsLayout
)
qp = QgsProject.instance()
md = qp.metadata()
md.setTitle('proj title')
md.setAuthor('proj author')
#md.setCreationDateTime(QDateTime(QDate(2011, 5, 3), QTime(9, 4, 5), QTimeZone(36000)))
md.setIdentifier('proj identifier')
md.setAbstract('proj abstract')
md.setKeywords({'kw': ['kw1', 'kw2'], 'KWx': ['kw3', 'kw4']})
qp.setMetadata(md)
l = QgsLayout(qp)
l.initializeDefaults()
exporter = QgsLayoutExporter(l)
# setup settings
settings = QgsLayoutExporter.ImageExportSettings()
settings.dpi = 80
rendered_file_path = os.path.join('D:\data', 'test_exporttoimagedpi.png')
result=exporter.exportToPdf('D:\data\TestLayout.pdf', settings)      
print(result)
print(exporter.errorFile())

If I run the above code, Python is stopped automatically without running complete code with the error:

python.exe – Application Error The instruction at 0x00007FFDA8AFCB4C
referenced memory at 0x0000000000000008. The memory could not be read.
Click on OK to terminate the program

If I run line by line and found that the line l = QgsLayout(qp) causing for the python crashing.

Can you help me to sort out the problem?

Best Answer

Add two following lines before qp = QgsProject.instance():

qgs = QgsApplication([], False)
qgs.initQgis()

then, add the next line to the end of the script:

qgs.exitQgis()

An additional warning: You should convert ImageExportSettings() into PdfExportSettings() since you export the layout to pdf. Otherwise, you will get this error:

QgsLayoutExporter.exportToPdf(): arguments did not match any overloaded call

Related Question