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()
Answer
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'
No comments:
Post a Comment