qgispyqgis

Why does pyqgis not give error or warning, when opening project with invalid file path


I have a stand alone script, that opens a QGIS project file in order to extract details.

I accidentally moved a file and the script broke. Below is the interesting part.

QgsApplication.setPrefixPath("/usr", True)
project = QgsProject.instance()
qgs = QgsApplication([], False)
qgs.initQgis()

project.read('/home/jdoe/textproj.qgz') 
# invalid path, but does not fail or warn in any way

print(project)
# prints: <QgsProject:'/home/jdoe/textproj.qgz'(singleton instance)>
# no indication of any problems with loading file

Question 1 - Why no error?

I think everyone would expect it to fail (throwing an exception). Is there any good reason for it to behave different than failing?

Question 2 - How to properly load a project from a file?

Is there anything in my code that is is using the library differently than intended, which may partly explain why I got no errors?

Question 3 - How do I make sure it fails?

Of course I could write my own assertion to test if the path does point to a file. But I guess there could be other ways in which reading/loading a project file could fail. So what is the proper way of catching this right away?


Solution

  • project.read will return True if the file reading was successful, and False if it was not, see the documentation. So, it is giving an indication of whether it was successful, but in your code, it is currently not being checked for. A simple if-else statement can catch the failure, which you can then adjust to do with what you want, such as quit the code or loop, or give a warning, for a super simple example:

    if project.read('/home/jdoe/textproj.qgz'):
        #read was successful
        print('Project successfully opened!')
    else:
        #read was unsuccessful
        print('Reading project file failed!)
    

    As for your first question, I cannot address this as I am not a QGIS developer, but you may have more luck asking in one of the mailing lists.