I want my script to do different things depending on whether a particular layer DOES or DOES NOT exist in the Map Layers list. I thought the try: / except: statements would be the best way to achieve this.
Here is a simplified version of my code:
checker = ' ' try: vl = QgsMapLayerRegistry.instance().mapLayersByName('mapLayerX') boolean = qgis.utils.iface.legendInterface().setCurrentLayer(vl) # if 'vl' exists boolean == "True" checker+='A, ' except: boolean = False checker+='B, ' if boolean == True: checker+='C, ' print checker
I'll look separately at the 2 possible scenarios (mapLayerX absent vs. mapLayerX present).
LAYER IS ABSENT:
Both the Console and the Tool print the same CORRECT result for 'checker': "B, " indicating ONLY the EXCEPT statement is executed (as it should be in those cases).
LAYER IS PRESENT:
FROM THE CONSOLE the code again works perfectly. The TRY statement executes as it should, setting boolean to 'TRUE' in response to the fact the setCurrentLayer function found "mapLayerX". This means the IF statement also executes, and the EXCEPT statement is ignored. The end result: 'checker' is printed as "A, C, "
But run AS A TOOL the code does the OPPOSITE! The TRY statement appears to be completely ignored somehow (which of course means the IF statement is too) and instead the EXCEPT statement is executed. The end result: 'checker' is printed as "B, "
SUMMARY TABLE (results of "print checker"): Console: Tool: Layer Present: A,C, B, Layer Absent: B, B,
*** when the Layer is Present the results should ALWAYS be "A, C, "
Any ideas why the same script runs incorrectly as a Tool (perhaps there are more appropriate Python statements to use here)? I'm using Q version 2.8.2.