1

I would like to write a Python script in the QGIS processing framework allowing the download of files from specific addresses.

Instead of starting my script with: vectorLyr = vector

I would like to have something like: vectorLyr = QgsVectorLayer("D:\...\shape_name.shp", "shape_name", "ogr")

In fact it works when I test the algorithm but fails when I want to save the program in the treatment toolbox (script considered not valid).

I can't find any solution.

Here is a simple programm showing a layer

In the first case I will have to select the layer manually:

##vectorLyr = vector
QgsMapLayerRegistry.instance().addMapLayers([vectorLyr,], True)

In this case the selection is automated:

##vectorLyr = QgsVectorLayer("D:\...\shape_name.shp", "shape_name", "ogr")
QgsMapLayerRegistry.instance().addMapLayers([vectorLyr,], True)

I have tried both options. They work fine but the 2d can't be downloaded as a treatment processing script (I have an error message).

My objective is to write a script:

  • which can be executed directly from the processing treatment tool box.(ex "Carte_Affectation2" in the picture)
  • able to download automatically a layer from a specific address. (I don't want to select it each time i run the sript)

Illustration:

Script involving a manual selection of the layer (##vectorLyr = vector):

Script involving an automatic selection of the layer (##vectorLyr = QgsVectorLayer("D:\...\shape_name.shp", "shape_name", "ogr"))

enter image description here

1
  • 1
    I think you need to include a much more complete script in your question. Commented May 7, 2016 at 9:21

1 Answer 1

0

You're close! You might be receiving errors because when you run code from the script, you need to import the relevant modules for the code to run. QGIS loads most of these at startup but the scripts are externally run. Modifying your code slightly, you could use:

##Example=name

from qgis.core import QgsVectorLayer, QgsMapLayerRegistry

vectorLyr = QgsVectorLayer("D:\...\shape_name.shp", "shape_name", "ogr")
QgsMapLayerRegistry.instance().addMapLayers([vectorLyr,], True)

Note that the name of the loaded layer would be "shape_name" and not the actual name of the layer (i.e. "example.shp" will still be called "shape_name" when loaded into QGIS).


If you want the actual shapename, you could use:

##Example=name

import os, qgis

path = "D:\...\shape_name.shp"
vectorLyr = qgis.utils.iface.addVectorLayer(path, os.path.splitext(os.path.basename(path))[0], "ogr")

You should be able to save both these code as scripts and run them from Processing.

1
  • @jean - Most welcome! Glad it worked :)
    – Joseph
    Commented May 16, 2016 at 9:28

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.