Tuesday, 14 February 2017

spatial join - Fails to run JoinAttributes in stand-alone PyQGIS script


I'm writing a stand-alone script using no GUI. I cannot use the function Join Attributes by Location. I think that the problem might be with proper passing arguments to the function. There's a piece of the code:


from qgis.core import *

from qgis.utils import *
import os,sys


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


sys.path.append('C:/OSGEO4~1/apps/qgis/python/plugins')

print sys.path

from processing.algs.qgis.JoinAttributes import *
alg = JoinAttributes()

alg.setParameterValue('INPUT_LAYER',QgsVectorLayer("C:\Points.shp",'pkt','ogr')) #all of those layers exist
alg.setParameterValue('INPUT_LAYER_2',QgsVectorLayer("C:\Polygons.shp",'polygons','ogr'))
alg.setOutputValue('OUTPUT_LAYER', QgsVectorLayer("C:\Ewid.shp",'CadastralLayer','ogr'))

from processing.gui.SilentProgress import SilentProgress

progress = SilentProgress()
alg.processAlgorithm(progress)

The error is as follows:


Original exception was:
Traceback (most recent call last):
File "mainScript.py", line 33, in aCD.addCadastralData(layers,parcelLayerPath)
File "Z:\Soft\AutomatyczneRaportowanie\AddingCadastralData\AddingCadastralData_main.py", line 36, in addCadastralData alg.processAlgorithm(progress)
File "C:/OSGEO4~1/apps/qgis/python/plugins\processing\algs\qgis\JoinAttributes.py", line 76, in processAlgorithm layer.crs())
File "C:/OSGEO4~1/apps/qgis/python/plugins\processing\core\outputs.py", line 308, in getVectorWriter crs, options)

File "C:/OSGEO4~1/apps/qgis/python/plugins\processing\tools\vector.py", line 550, in __init__ if self.destination.startswith(self.MEMORY_LAYER_PREFIX):
AttributeError: 'NoneType' object has no attribute 'startswith'

Could you help me to sort it out?



Answer



You use a backslash within quotes in your parameters. In python this is a escape character.


Use r"c:\" or use forward slashes "c:/" or double backslashes "c:\\" to avoid the escape charakter. And try to be consistent about it as you are mixing them in your code. (sys.path.append with forward slashes for example). Its also a good idea not to mix single and double quotes even when it does not matter here.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...