I wrote a simple script in startup.py, but when I open a QGIS project, I appear a python error window. The "contratos" layer is a PostGIS layer. But I tried with a regular layer and the error persist.


from qgis.core import QgsProject
layer = QgsProject.instance().mapLayersByName("contratos")[0]

The Python error notification:

An error occurred during execution of following code: spec.loader.exec_module(module) Traceback (most recent call last): File "", line 1, in File "", line 728, in exec_module File "", line 219, in _call_with_frames_removed File "C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3/startup.py", line 2, in layer = QgsProject.instance().mapLayersByName("contratos")[0] IndexError: list index out of range Python version: 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] QGIS version: 3.8.3-Zanzibar 'Zanzibar', 685d8b15d2 Python path: ['C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python', 'C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3\profiles\default/python', 'C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins', 'C:/PROGRA~1/QGIS3~1.8/apps/qgis/./python/plugins', 'C:\PROGRA~1\QGIS3~1.8\bin\python37.zip', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37\DLLs', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib', 'C:\PROGRA~1\QGIS3~1.8\bin', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\win32', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\win32\lib', 'C:\PROGRA~1\QGIS3~1.8\apps\Python37\lib\site-packages\Pythonwin', 'C:/Users/vitor.machado/AppData/Roaming/QGIS/QGIS3\profiles\default/python']

Window capture enter image description here


You get this error message when QGIS can't identify your layer. Your layer should not be loaded.

You can write your command line in a function that runs when QGIS initialization is completed. You can follow the following example :

from qgis.utils import iface
from qgis.core import QgsProject

## Function
def your_layer():
    layer = QgsProject.instance().mapLayersByName("contratos")[0]

## When the initialization of QGIS is complete, we launch the your_layer function

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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