I am having trouble with the last phase of a script for a script tool: I cannot figure out how to delete my temporary gdb to close out the script. Having the program that's executing the script open retains a lock in the gdb...for instance when I close Jupyter (or VS code, or IDLE) I can see the lock file in the gdb disappear. How can I construct my code so this isn't an issue when made into a script tool?
The general advice that I have seen has been to add an arcpy.env.overwriteOuput = True, and that has not been effective. I have also seen suggestions to work in memory but I would rather be able to review the intermediate outputs.
The code that creates the gdb:
#Create temporary Workspace
arcpy.AddMessage("\nCreating temporary workspace")
tempName = "incorp" + outVersion + "_TEMP"
tempGDB = os.path.join(outFolder, tempName + ".gdb")
arcpy.management.CreateFileGDB(outFolder, tempName)
arcpy.env.workspace = tempGDB
arcpy.env.overwriteOutput = True
The script then goes on and does several operations within that temp gdb, clipping, erasing, querying, adding fields, etc. Then when I go to delete it...
#Delete intermediate data
arcpy.AddMessage("\nDeleting intermediate data")
todel = (tempGDB, union, lastIncorp_xml)
for dataset in todel:
if arcpy.Exists(dataset):
arcpy.management.Delete(dataset)
I get ERROR 000601 - Cannot delete [path].gdb. May be locked by another application. Failed to execute (Delete).
Any thoughts on what can be done so the tool can clean up after itself?
1 Answer 1
I ended up just using "memory" as the workspace and that did the trick. I still don't really understand what was holding it open but this change did the trick.
An example...
#Set memory workspace
arcpy.AddMessage("\nCreating temporary workspace")
memory = r"memory"
arcpy.env.workspace = memory
#Clip by boundary layer
arcpy.AddMessage("\nClipping to state boundary")
boeClipped = os.path.join(memory, "boeClipped")
arcpy.analysis.Clip(boeDataSet, boundary, boeClipped)
And a note to rookies like me you still have to delete the in-memory layers to close out the script, otherwise you won't be able to run the tool twice.
env.workspace
locks it open. You can't delete an open workspace. You must first remove the lock by assigning a different default workspace.