1

I wrote several python scripts called by my main.py script. In one of those scripts I create a vector layer by polygonizing a raster layer. As the layer is really heavy and as I don't need it as an output, I create it in memory.

result = processing.runalg('gdalogr:polygonize',layer,"lu_majorit", None)
polygonLayer = processing.getObject(result['OUTPUT'])

Then I can use the layer in my file. But I would like to use this layer from another script and I don't succeed.

Here is what I've tried :

in my first script :

result = processing.runalg('gdalogr:polygonize',layer,"lu_majorit", None)
polygonLayer = processing.getObject(result['OUTPUT'])
return polygonLayer

in my main:

polygonLayer=script1(...)
script2(polygonLayer,...)

in my second script :

cLayer =QgsVectorLayer("Polygon?crs=epsg:4326", "OUTPUT", "memory")

or:

cLayer =QgsVectorLayer("polygonLayer", "OUTPUT", "ogr")

Those two ways failed to load the layer.

I tried also by giving the path with : script 1 :

myfilepath= polygonLayer.dataProvider().dataSourceUri()
return myfilepath

script2:

cLayer =QgsVectorLayer(myfilepath, "OUTPUT", "ogr")

This way gives me an invalid syntax.

Does someone know how to do ?

  • instead of runalg you can use runandload ( load it to QgsMapLayerRegistry and use it later ) like here gis.stackexchange.com/questions/76594/… – Hicham Zouarhi Jul 17 '17 at 13:40
  • @HichamZouarhi When I replace runalg by runanload I get this message error : "polygonize has no attribute 'getitem'" – J.Delannoy Jul 17 '17 at 15:19
1

If both your python files are in the same directory, something like this should work:

script2

def myFunction():
    result = processing.runalg('gdalogr:polygonize',layer,"lu_majorit", None)
    polygonLayer = processing.getObject(result['OUTPUT'])
    return polygonLayer

main script

import script2 # for python file named script2.py

polygonLayer = script2.myFunction()

If they are not in the same directory you may use the sys.path.append() method to append the path of the python script you want to add:

sys.path.append('//path/to/other/script/directory')
import script2
  • Thank you for your answer. My files are in the same directory and I tried this method. But this does not work. It failed to load the layer – J.Delannoy Jul 19 '17 at 12:43
  • Can you expand more on what you mean by "failed to load the layer"? – artwork21 Jul 19 '17 at 13:44
  • It works !!! I think that I tried too many ways so I mixed up some ... So now that I cleaned my code to explain better my problem, there is no problem anymore. So thank you :) – J.Delannoy Jul 20 '17 at 6:50

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.