1

I am running a Python script in QGIS 2.18.26 and I have a select by location with a code like that:

indir = "C:/Infolder/"  
outdir = "C:/Outfolder/"  

os.chdir(indir)  

for fname in glob.glob("*.shp"):  
    layerResult = processing.getObject(fname)

    QgsMapLayerRegistry.instance().addMapLayer(layerResult)
    processing.runalg("qgis:selectbylocation", layerResult, "C:/SomePolygon.shp", u'within',0,0)

    result= outdir + 'Test' + fname
    processing.runalg('qgis:saveselectedfeatures', layerResult, result)
    #processing.load(result)
    QgsMapLayerRegistry.instance().removeMapLayers( [layerResult.id()] )

In case there is no section, I receive a pop-up window as follows: enter image description here

I want to avoid that pop-up window because it slows down the whole process.

Can you please advise how I can get rid of it?

1

You can add an if statement to check if any features are selected:

if layerResult.selectedFeatures():

If there are selected features then run the second algorithm otherwise do something else. So your script could look like:

indir = "C:/Infolder/"  
outdir = "C:/Outfolder/"  

os.chdir(indir)  

for fname in glob.glob("*.shp"):  
    layerResult = processing.getObject(fname)

    QgsMapLayerRegistry.instance().addMapLayer(layerResult)
    processing.runalg("qgis:selectbylocation", layerResult, "C:/SomePolygon.shp", u'within',0,0)

    if layerResult.selectedFeatures():
        result= outdir + 'Test' + fname
        processing.runalg('qgis:saveselectedfeatures', layerResult, result)
        #processing.load(result)
        QgsMapLayerRegistry.instance().removeMapLayers( [layerResult.id()] )
    else:
        # do something else

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.