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– Hicham Zouarhi2017年07月17日 13:40:37 +00:00Commented Jul 17, 2017 at 13:40
-
@HichamZouarhi When I replace runalg by runanload I get this message error : "polygonize has no attribute 'getitem'"J.Delannoy– J.Delannoy2017年07月17日 15:19:49 +00:00Commented Jul 17, 2017 at 15:19
1 Answer 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 layerJ.Delannoy– J.Delannoy2017年07月19日 12:43:19 +00:00Commented Jul 19, 2017 at 12:43
-
Can you expand more on what you mean by "failed to load the layer"?artwork21– artwork212017年07月19日 13:44:56 +00:00Commented Jul 19, 2017 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– J.Delannoy2017年07月20日 06:50:29 +00:00Commented Jul 20, 2017 at 6:50