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 do the trick nicely.
Here is a simplified version of my code:
checker = ' ' try: vl = QgsMapLayerRegistry.instance().mapLayersByName('mapLayerX')[0] 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 checkerThere are obviously TWO scenarios in which the code can execute: either the layer is present or it isn't. I'll look at each separately.
LAYER IS ABSENT:
Both the Console and the Tool print the same CORRECT result for 'checker': 'B,' indicating the EXCEPT statement is executed (as it should be in those cases).
LAYER IS PRESENT:
When I run this code in the Console it 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. The end result: 'checker' is printed as "A, C,"
But when I run the code via a Tool the opposite occurs. The TRY statement appears to be ignored and the EXCEPT statement is executed. 'checker is printed as "B,"
Summary Table ("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)?
أكثر...
Here is a simplified version of my code:
checker = ' ' try: vl = QgsMapLayerRegistry.instance().mapLayersByName('mapLayerX')[0] 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 checkerThere are obviously TWO scenarios in which the code can execute: either the layer is present or it isn't. I'll look at each separately.
LAYER IS ABSENT:
Both the Console and the Tool print the same CORRECT result for 'checker': 'B,' indicating the EXCEPT statement is executed (as it should be in those cases).
LAYER IS PRESENT:
When I run this code in the Console it 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. The end result: 'checker' is printed as "A, C,"
But when I run the code via a Tool the opposite occurs. The TRY statement appears to be ignored and the EXCEPT statement is executed. 'checker is printed as "B,"
Summary Table ("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)?
أكثر...