1

I am trying to work with an active QGIS from a jupyter notebook - specifically I'd like to be able to access iface so I can perform some layer calculations.

I am having trouble getting the map layers and working with the iface.

from qgis.core import *
import qgis.utils
from qgis.utils import iface, plugins

import numpy
import pandas
import pathlib, os, sys

 
project_name= r"C:\path-to-project.qgz"
app= QgsApplication([], False)
QgsApplication.setPrefixPath(r"C:\OSGeo4W\apps\qgis", True)
QgsApplication.initQgis() 

current_project= QgsProject.instance()
current_project.setFileName(project_name)
print(current_project) #this prints a project instance

print(current_project.mapLayers()) #this returns an empty dictionary {}

layer = iface.activeLayer() #this gives an error: NoneType has no method activeLayer

layers = iface.mapCanvas().layers() #same error as above: it thinks iface is None

For some reason it is not able to use iface and gives me a NoneType error.

How do I work with the currently running QGIS instance from a jupyter notebook and have access to the map layers?

0

My question was similar to Listing project layers in standalone PyQGIS script.

What ended up working was:

from qgis.core import *    
from PyQt5.QtCore import QFileInfo    
import os
from PyQt5 import QtCore, QtGui, QtWidgets
from os.path import expanduser
from qgis.core import QgsApplication

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

QgsApplication.initQgis()

fname = r"C:\path-to-project.qgz"
# Get the project instance
project = QgsProject.instance()
# Open the project
project.read(fname)
print(project.fileName())

map_layers = QgsProject.instance().mapLayers().values()
print(map_layers) #this now has the layers in a dictionary

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.