In my standalone python 3 script, QgsVectorLayer() is loading an invalid layer. When I use the exact same function and inputs in the QGIS GUI python console, the layer loads fine. I am not sure what is missing in my standalone script. I have double checked the paths and made sure they are correct. I used
QgsApplication.prefixPath()
to check the correct path for input in the
QgsApplication.setPrefixPath()
function within my standalone script. The path and inputs I use in the
QgsVectorLayer()
function in my standalone script are the same as those used in the GUI python console. I'm not sure why loading a vector layer in my standalone script it failing. The vector object is created, but .isValid() returns False.
Here is my standalone script:
import sys, os, time
sys.path.extend([r'C:\OSGeo4W\apps\qgis\python',r'C:\OSGeo4W\apps\Python37\Lib\site-packages'])
#modify environment variables to find qgis and qt plugins during qgis.core import
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'C:\OSGeo4W\apps\Qt5\plugins'
os.environ['QT_PLUGIN_PATH'] = r'%QT_PLUGIN_PATH%;C:\OSGeo4W\apps\Qt5\plugins;C:\OSGeo4W\apps\qgis\qtplugins;C:\OSGeo4W\apps\qgis\plugins'
os.environ['PATH'] += r';C:\OSGeo4W\apps\qgis\bin;C:\OSGeo4W\apps\Qt5\bin;C:\OSGeo4W\\bin'
from qgis.core import *
from qgis.gui import *
# supply path to qgis install location
QgsApplication.setPrefixPath(r'C:\OSGeo4W\apps\qgis', True)
#QgsApplication.setPluginPath('C:\\OSGeo4W\\apps\Qt5\\plugins\\platforms')
#print(QgsApplication.systemEnvVars())
# create a reference to the QgsApplication
# setting the second argument to True enables the GUI, which we need to do
# since this is a custom application
qgs = QgsApplication([], True)
# load providers
qgs.initQgis()
##########################
# Write your code here to load some layers, use processing algorithms, etc.
canvas = QgsMapCanvas()
canvas.show()
layer = QgsVectorLayer(r'C:\Users\Matt\OneDrive\FarmProject\Kankakee_Parcels\K3_TaxParcels.shp', 'Kankakee', 'ogr')
if not layer.isValid():
print('Failed to open the layer')
# add layer to the registry
add_layers = QgsProject.instance().addMapLayer(layer)
# set extent to the extent of our layer
canvas.setExtent(layer.extent())
# set the map canvas layer set
canvas.setLayers([add_layers])
canvas.refresh()
time.sleep(30)
########################
# When your script is complete, call exitQgis() to remove the provider and
# layer registries from memory
qgs.exitQgis()
-
This answer might help you to set correctly your QGIS prefix: gis.stackexchange.com/questions/155745/…Germán Carrillo– Germán Carrillo2019年01月11日 22:21:45 +00:00Commented Jan 11, 2019 at 22:21
2 Answers 2
Per the solution found at this link: https://github.com/OSGeo/homebrew-osgeo4mac/issues/197
The QgsApplication.setPrefixPath() is not correctly setting the prefix. Therefore, the vector layer cannot load properly.
A workaround is to set the QGIS prefix environment variable directly using the os module in Python:
os.environ['QGIS_PREFIX_PATH'] = r'prefix\path'
Once the prefix path is correctly set, the vector layer should load properly and .isValid() should yield 'True'
I had the same problem, but I solved it with:
os.environ ['QGIS_PREFIX_PATH'] = 'C: \\ OSGeo4W64 \\ apps \\ qgis'
os.environ ['QGIS_PREFIX_PATH'] = 'C: \ OSGeo4W64 \ apps \ qgis'
Look at the example:
import sys
import os
os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'C:\\OSGeo4W64\\apps\\Qt5\\plugins'
os.environ['PATH'] += ';C:\\OSGeo4W64\\apps\\qgis\\bin;C:\\OSGeo4W64\\apps\\Qt5\\bin'
from qgis.core import QgsApplication, QgsProcessingFeedback,QgsVectorLayer
from qgis.analysis import QgsNativeAlgorithms
QgsApplication.setPrefixPath('C:\\OSGeo4W64\\apps\\qgis', True)
os.environ['QGIS_PREFIX_PATH'] = 'C:\\OSGeo4W64\\apps\\qgis'
qgs = QgsApplication([], False)
qgs.initQgis()
# Add the path to processing so we can import it next
sys.path.append('C:\\OSGeo4W64\\apps\\qgis\\python\\plugins')
import processing
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())
feedback = QgsProcessingFeedback()
########################################################################################
ruta = 'C:\\Users\\' + os.getlogin() +'\\Desktop\\ProyectoAgrupaciones\\Distrito\\UGM_30101_region.shp'
capa = QgsVectorLayer(ruta, 'UGM_30101_region', 'ogr')
for x in capa.getFeatures():
print(x["ID"])
for field in capa.fields():
print(field.name(), field.type())
if capa.isValid():
print("CAPA CARGADA")
else:
print("ERROR CAPA NO CARGADA")
#CALCULA LOS CENTROIDES DE TODOS LOS POLIGONOS, GENERA UN .shp ('rutaCapaCentroides').
centroides = processing.run("native:centroids", {
'INPUT': "C:\\Users\\Arturo Guillen\\Desktop\\ProyectoAgrupaciones\\Distrito\\UGM_30101_region.shp",
'ALL_PARTS': False,
'OUTPUT':"C:\\Users\\Arturo Guillen\\Desktop\\ProyectoAgrupaciones\\Centroides\\UGM_30101_region_centroides.shp"
})
print("Se ha generado la capa de CENTROIDES:",centroides)
########################################################################################
qgs.exitQgis()