I have a script which removes a layer from the MXD, and then re-creates the feature from scratch in a GDB and adds the layer back in.
If I remove the layer manually before running the script, it runs fine. But if I remove the layer in the script, the script later fails when trying to re-create the GDB due to a lock. This is resolved by reloading the MXD.
Traceback (most recent call last): File "D:\RouteSmart_Work\Tools and Utilities\Python - Street Assignment Visualiser\StreetAssignment.py", line 60, in arcpy.CreateFileGDB_management(outputFolder, "StreetAssignments.gdb") File "c:\program files (x86)\arcgis\desktop10.3\arcpy\arcpy\management.py", line 16594, in CreateFileGDB raise e ExecuteError: ERROR 999999: Error executing function. Failed to execute (CreateFileGDB).
I've tried implementing arcpy.Compact_management (credit to StacyR from another and gc.collect() but these still don't seem to clear the lock. Could anyone advise if I'm missing anything? The script is meant to be run frequently, without the need to remove the layer each time.
def clearWSLocks(inputWS): '''Attempts to clear locks on a workspace, returns stupid message.''' if all([arcpy.Exists(inputWS), arcpy.Compact_management(inputWS), arcpy.Exists(inputWS)]): return 'Workspace (%s) clear to continue...' % inputWS else: return '!!!!!!!! ERROR WITH WORKSPACE %s !!!!!!!!' % inputWS arcpy.env.overwriteOutput = True servLoc_layer = arcpy.GetParameterAsText(0) streets_layer = arcpy.GetParameterAsText(1) outputFolder = arcpy.GetParameterAsText(2) # Remove the layer if it's already in the data frame mxd = arcpy.mapping.MapDocument("CURRENT") df = arcpy.mapping.ListDataFrames(mxd) if arcpy.Exists("FC"): # Use name rather than layer object in case name doesn't exist lyr = arcpy.mapping.Layer("FC") # Create layer object in order to remove it arcpy.mapping.RemoveLayer(df, lyr) arcpy.RefreshActiveView() del lyr, df, mxd outGDB = os.path.join(outputFolder, "GDB.gdb") # Geodatabase xyLineOutput = os.path.join(outGDB,"FC") if arcpy.Exists(xyLineOutput): arcpy.Delete_management(xyLineOutput) gc.collect() if arcpy.Exists(outGDB): arcpy.AddMessage(clearWSLocks(outGDB)) arcpy.Delete_management(outGDB) arcpy.CreateFileGDB_management(outputFolder, "GDB.gdb")
In this instance I've instructed the user to remove the layer manually before running the script, to keep the one GDB as the workspace. It's only a small geoprocessing task, so the data management will be simple. I will bear Vince's comment in mind for the future.