5

Very simple piece of code. I'm trying to run this as a stand alone Python script, not in the console. Keeps giving the error "Could not load source layer for INPUT", shape not found. But the os.path.isfile commands shows that the shapefile does exist. Driving me crazy this one problem. Been looking for solution for 2 days.

import sys, os
sys.path.extend([r'E:\sw_nt\QGIS_3.4\apps\qgis\python',r'E:\sw_nt\QGIS_3.4\apps\Python37\Lib\site-packages'])

os.environ['QT_QPA_PLATFORM_PLUGIN_PATH'] = r'E:\sw_nt\QGIS_3.4\apps\Qt5\plugins'
os.environ['PATH'] += r';E:\sw_nt\QGIS_3.4\apps\qgis\bin;E:\sw_nt\QGIS_3.4\apps\Qt5\bin'

sys.path.append(r'E:\sw_nt\QGIS_3.4\apps\qgis\python')
sys.path.append(r'E:\sw_nt\QGIS_3.4\apps\qgis\python\plugins')
sys.path.append(r'E:\sw_nt\QGIS_3.4\apps\qgis\python\plugins\processing')

from qgis.core import (
     QgsApplication, 
     QgsProcessingFeedback, 
     QgsVectorLayer
)


from qgis.analysis import QgsNativeAlgorithms

QgsApplication.setPrefixPath('/usr', True)
qgs = QgsApplication([], False)
qgs.initQgis()


import processing
from processing.core.Processing import Processing
Processing.initialize()
QgsApplication.processingRegistry().addProvider(QgsNativeAlgorithms())

feedback = QgsProcessingFeedback()


rivers = r'W:\srm\wml\Workarea\mamcgirr\QGIS_learning_projects\ne_10m_rivers_lake_centerlines.shp'
output = r'W:\srm\wml\Workarea\mamcgirr\QGIS_learning_projects\bcgw_test_data_as_shapes\clean_polys\danube3.shp'
expression = "name LIKE '%Danube%'"

print (os.path.isfile(rivers))


danube = processing.run(
    'native:extractbyexpression',
    {'INPUT': rivers, 'EXPRESSION': expression, 'OUTPUT': output},
    feedback=feedback
    )['OUTPUT']


print(danube)
3
  • Have you tried using forward slashes instead of back slash in the path? – strythe Apr 12 '19 at 6:47
  • I tired this. Exact same result. – Mark McGirr Apr 15 '19 at 14:33
  • Perhaps there is some library not being loaded. I tried loading the 'modified script' another person submitted, but it looked exactly the same as the script I loaded. – Mark McGirr Apr 15 '19 at 17:36
1

I met the same problem as You. I'm new to Python, but I found it worked to use a QgsVecotrLayer instance instead of the layer path. Change the defination of rivers to

rivers = QgsVectorLayer("r'W:\srm\wml\Workarea\mamcgirr\QGIS_learning_projects\ne_10m_rivers_lake_centerlines.shp'","rivers","ogr")

By the way, if you get the direct solution please share with me.

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.