PyQGIS – Listing Project Layers in Standalone PyQGIS Script

layerslistpyqgis

I'm trying to load an existing .qgs project and get a list of the layers inside. I seem to be able to open the project, but I can't get the list of layers. I'm a little confused as to the basic PyQGIS syntax, and the cookbook doesn't cover this specific example.

from qgis.core import *
from PyQt4.QtCore import QFileInfo


QgsApplication.setPrefixPath(r"C:\OSGeo4W\apps\qgis-ltr", True)
qgs = QgsApplication([], False)
qgs.initQgis()
# Get the project instance
project = QgsProject.instance()
# Open the project
project.read(QFileInfo(
        r'C:\path\to\project\project.qgs'))
print project.fileName()
# Get the layers in the project
layers = QgsMapLayerRegistry.instance().mapLayers()

print layers
qgs.exitQgis()

Currently, this just layers returns an empty dict, despite the fact that the project exists and has many layers in it.

Best Answer

I also receive an empty dictionary when I run your code but the following works for me which is slightly different:

from qgis.core import *
from PyQt4.QtCore import QFileInfo
from PyQt4.QtGui import QApplication
import os

from os.path import expanduser
home = expanduser("~")

QgsApplication( [], False, home + "/AppData/Local/Temp" )
QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
app = QApplication([], True)
QgsApplication.initQgis()

# Get the project instance
project = QgsProject.instance()
# Open the project
project.read(QFileInfo('C:\path\to\project\project.qgs'))
print project.fileName()
# Get the layers in the project
layers = QgsMapLayerRegistry.instance().mapLayers()
print layers

QgsApplication.exitQgis()
app.exit()

Tested on QGIS 2.18.3 for Windows 7 64-bit.

Result



Edit:

The main difference, I believe, between your code and what I used is that you need to create the QApplication object before creating the QgsApplication. So you would need to replace:

qgs = QgsApplication([], False)

with this:

qgs = QApplication([], False)

But the QApplication class needs to be imported so we must add the following:

from PyQt4.QtGui import QApplication

And finally, if you want to do a cleanup, you need to add the following at the end.

QgsApplication.exitQgis()

So you could try using the following code which is more close to your original code:

from qgis.core import *
from PyQt4.QtCore import QFileInfo
from PyQt4.QtGui import QApplication

QgsApplication.setPrefixPath("C:/OSGeo4W64/apps/qgis", True)
qgs = QApplication([], False)
QgsApplication.initQgis()
# Get the project instance
project = QgsProject.instance()
# Open the project
project.read(QFileInfo('C:/path/to/project/project.qgs'))
print project.fileName()
# Get the layers in the project
layers = QgsMapLayerRegistry.instance().mapLayers()

print layers
QgsApplication.exitQgis()
Related Question