I have the code :

from qgis.core import QgsMapLayerRegistry
vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]

When I type in console after loading QGIS, no error. But, when I put the code in startup.py, so automatically QGIS will execute the code in startup.py, I get error. The error : "list index out of range"

What is wrong for the code?

  • 3
    Generally it means you are calling something that doesn't exist. So I assume when you have QGIS open and use the console, your object exists, but when you call your code in startup.py the object doesn't yet exist...
    – nmtoken
    Mar 2, 2017 at 8:14

1 Answer 1


You probably need to preliminarily import the layer before calling it.

If pl is a shapefile:

from qgis.core import *
layer =  QgsVectorLayer('C:/Users/path_to_shapefile/vector_layer.shp', 'pl' , "ogr")
vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]

If pl is a raster:

from qgis.core import *
layer =  QgsRasterLayer('C:/Users/path_to_raster/raster_layer.tif', 'pl')
vl = QgsMapLayerRegistry.instance().mapLayersByName('pl')[0]
  • 2
    Nice answer! I would just like to add that when adding any layers from the startup.py script, it is probably best to define a function which loads the layers and run this function when QGIS has finished the initialisation process as was asked in this post. Otherwise the annoying notification message appears :)
    – Joseph
    Mar 3, 2017 at 11:31
  • It is work. But, there is annoying notification as in this post : gis.stackexchange.com/questions/226298/…. I can not combine the code to remove notification. Should I ask a new question?
    – mega
    Mar 6, 2017 at 1:32
  • @mega I think you are asking some help for a new topic. Assuming that it's not a duplicate of the question in the link that you shared, I suggest you accepting this answer (it seems it solved the error: "list index out of range") and asking a new question.
    – mgri
    Mar 6, 2017 at 13:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.