I'd like to automate a layer rasterization process using PyQGIS but the first step---obtaining a list of the layers to rasterize---is failing in QGIS 2.18.9 on Windows 10. What am I missing? Regardless of which project it's pointed to or whether Python is running from an IDE or the OSGeo4W shell directly the test script below always indicates zero layers even though project.read() always returns true.
import sys
sys.path.append('C:/Program Files/QGIS 2.18/apps/qgis/python')
from qgis.core import *
from PyQt4.QtCore import QFileInfo
qgis = QgsApplication([], False)
# EDIT: setPrefixPath() resolves the issue per Germán Carrillo's answer below
qgis.setPrefixPath('C:/Program Files/QGIS 2.18/apps/qgis', True)
qgis.initQgis()
project = QgsProject.instance()
project.read(QFileInfo('C:/Users/<username>/Documents/<path>/<project>.qgs'))
layers = project.layerTreeRoot()
print len(layers.children()), "layers loaded"
qgis.exitQgis()
I'm aware of this question and the code above conforms to a number of other similar examples which are supposed to work. Using QgsApplication([], True) or various other flavours of the above calls makes no difference. QgsMapLayerRegistry.instance().mapLayers() is also empty.
If the same projects are opened in the regular QGIS UI querying:
QgsProject.instance().layerTreeRoot().children()
from the Python console contains all layers as expected. Having the project open in QGIS proper versus not having QGIS running has no effect on the external Python python behavior. So this doesn't look like contention between QGIS instances.