Geographic Information Systems Asked by Alexandr Crit on March 18, 2021
Python script using QGIS package terminates suddenly when calling QgsProject.write.
Idea is to create QGIS Project with select list of files and save it to disk, in automated manner.
Script:
from qgis.core import QgsProject, QgsRasterLayer
def foo():
filePath = "C:/Users/username/Documents/projects/GeoTiffSample.tiff"
savePAth = "C:/Users/username/Documents/projects/test2.qgs"
proj = QgsProject.instance()
proj.setFileName(savePAth)
testlayer = QgsRasterLayer(filePath, baseName = "testLayer")
proj.addMapLayer(testlayer)
proj.setFileName(savePAth)
proj.setDirty(True)
try:
print("Prewrite")
ret = proj.write()
print("Postwrite")
pass
except Exception as exc:
print(exc)
print(ret)
print("START")
try:
foo()
except Exception as exc:
print(exc)
print("END")
Output:
START
Prewrite
Documentation is kind of lacking on any info. I suspect unhandeled exception in QGIS library.
Double checked documentation and cookbook (https://docs.qgis.org/3.4/en/docs/pyqgis_developer_cookbook/intro.html#pythonapplications) "Using PyQGIS in custom applications". The I simply needed to initiate QGIS app.
from qgis.core import QgsProject, QgsRasterLayer, QgsApplication
#Optional line: QgsApplication.setPrefixPath("/path/to/qgis/installation", True)
#I don't have qgis installed and simply using pyqgis package, so line was ommited
qgs = QgsApplication([],True)
qgs.initQgis() #initiate QGIS
#Enter your code here
qgs.exitQgis() #free resources
Problem solved. But it would be rather nice of developer to add error message.
Answered by Alexandr Crit on March 18, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP