1

I'm writing a standalone Python script which involves some geoprocessing using qgis libs. Unfortunetely, I couldn't manage to properly instantiate a vector layer - every time i run .isValid() on QgsVectorLayer instance, it returns False. I tried using both Shapefile and PostGIS layers.
I'm aware of the following threads:
* https://stackoverflow.com/questions/41449252/python-qgis-layer-failed-to-load
* Problem loading vector layer (pyQGIS)
but none of given answers resolves my problem.

Here is the output from QgsApplication.showSettings() :

Application path not initialized
Application path not initialized
Application path not initialized
Application state:
QGIS_PREFIX_PATH env var:               C:/OSGEO4~1/apps/qgis-ltr

Prefix:
Plugin Path:
Package Data Path:      C:/OSGEO4~1/apps/qgis-ltr
/.
Active Theme Name:
Active Theme Path:      C:/OSGEO4~1/apps/qgis-ltr
/./resources/themes\\icons/
Default Theme Path:     :/images/themes/default/
SVG Search Paths:
User DB Path:   C:/OSGEO4~1/apps/qgis-ltr
/./resources/qgis.db
Auth DB Path:   qgis-auth.db

And here is my code snippet

from qgis.core import *
import os
import sys

os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = 'C:\\OSGeo4W64\\apps\\Qt5\\plugins'
os.environ['PATH'] += 'C:\\OSGeo4W64\\apps\\qgis-ltr\\bin;C:\\OSGeo4W64\\apps\\Qt5\\bin'

QgsApplication.setPrefixPath("C:\\OSGEO4~1\\apps\\qgis-ltr", True)
qgs = QgsApplication([], False)
qgs.initQgis()

sys.path.append('C:\\OSGeo4W64\\apps\\qgis-ltr\\python\\plugins')
import processing

project = QgsProject.instance()

# Gminy.shp is a valid shapefile (opens in QGIS), containing a .shx file as well
tshp_layer = QgsVectorLayer("G:\\PRG_7.05.2019\\Gminy.shp", "test_lyr", "ogr")
# this returns false
print(str(tshp_layer.isValid()))

# connection to PostgreSQL DB using proper credentials works fine
uri = QgsDataSourceUri()
uri.setConnection("<host>", "5432", "<db_name>", "<user>", "<pass>")
uri.setDataSource("<schema>", "<table>", "<geometry_field>")
drogi_layer = QgsVectorLayer(uri.uri(False), "my_custom_layer_name", "postgres")
# this also returns false
print(str(drogi_layer.isValid()))

qgs.exitQgis()

print('All done!')

Which returns:

False
False
All done!
  • check your path, add "r" in your Gminy.shp path – Fran Raga Aug 22 at 9:32

Your Answer

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

Browse other questions tagged or ask your own question.