import arcpy # start of script try: todlt = [] # list to store everything I want to delete in the end. # ... body of the script, whatever ... my_buffer = arcpy.Buffer_analysis(...).getOutput(0) todlt.append(my_buffer) # if my_buffer is a temporary feature class my_buffer_lyr = arcpy.MakeFeatureLayer_management(my_buffer, 'lyrname', ...).getOutput(0) todlt.append(my_buffer_lyr) # my_buffer_lyr is a temporary feature layer # ... rest of the body of script ... except arcpy.ExecuteError as e: # handle ... except Exception as e: # handle ... finally: # cleanup if 'todlt' in dir(): for dl in todlt: try: arcpy.Delete_management(dl) except: arcpy.AddWarning('Could not delete temporary data ' + str(dl))
Adam,
I include that cleanup def() in just about all of my .py source files to any of the Geoprocess tools I build that utilize in_memory space. But like Curtis said, it's a little off topic to this thread.
Do you copy and paste this code into the console, or run it from somewhere else? See my post below; it'll be a good thing for me to add to my python package...
This is all great info, and I especially like the delete everything in memory function. I thought I'd throw my own two cents in also... I began to deal with deleting feature classes like this a while ago by creating my own little python module. It's super useful to have a some functions that you can call anytime from anywhere, because I need to do this "delete if exists" thing all the time (plus a lot of other stock operations that I'm tired of retyping).
Just make a folder in your python site-packages directory (something like C:\Python2x\Lib\site-packages, or, more likely, C:\Python2x\ArcGIS10.x\Lib\site-packages) called mypack, and then in that folder create a text file called __init__.py. You can define all the functions you want in there, and to access them from any console or script just say "from mymod import functionname".
For what we're talking about here, I just have this in the __init__.py file:
import arcpy
def TakeOutTrash(dataset):
if arcpy.Exists(dataset):
arcpy.management.Delete(dataset)
so in the console, making a feature layer could look like:
from mypack import TakeOutTrash
fl = "fl"
TakeOutTrash(fl) # this is important if you are iterating or running the script many times
arcpy.management.MakeFeatureLayer(r"path",fl)
##do some stuff with feature layer
TakeOutTrash(fl)
That function could be modified to accept a list of datasets too, I just haven't done that yet.
Aha, that's a good point about the locks, Curtics. So it's best to delete the layer as soon as you are done doing what you needed the layer (or table view) for.
Ah. Your Delete_management of FeatureLayers works for me too.
James, I believe we are discussing layers, not datasets (in_memory, on disk, or in an RDBMS). I realize I confused the thread a bit by including a table in my code sample. If you delete a feature class that is referenced by a open layer in memory, the Delete_management will not throw an error but the dataset will persist until the python session (not the script) is over. At least that's my experience.
For this reason, you'll see in my finally block that I listed layer first, then the dataset in my delete list.
I just call this def() before/after any in_memory processing. Seems legit.
def clearINMEM(): arcpy.env.workspace = r"IN_MEMORY" fcs = arcpy.ListFeatureClasses() tabs = arcpy.ListTables() ### for each FeatClass in the list of fcs's, delete it. for f in fcs: arcpy.Delete_management(f) arcpy.AddMessage("deleted: " + f) ### for each TableClass in the list of tab's, delete it. for t in tabs: arcpy.Delete_management(t) arcpy.AddMessage("deleted: " + t)
This is worth discussing further. The help is not explicit about this and it's too bad -- if you don't clean up your layers, you leave joins and file locks polluting your session -- especially with script tools launched in-process from ArcGIS Desktop.
Here's the approach that I have been using.
from datetime import datetime dtag = datetime.now().strftime("%Y%m%d%H%M%S") # '20140915110231' lyrName = "lyr" + dtag # set up temp variables tmp_layer, tmp_table = [None] * 2 try: # ... create tmp_table name tmp_table = arcpy.CreateScratchName("", dtag, "table") arcpy.CreateTable_management(os.path.dirname(tmp_table), os.path.basename(tmp_table)) tmp_layer = arcpy.MakeFeatureLayer(tmp_table, lyrName) # ... except: pass # normal error handling here finally: for f in [tmp_layer, tmp_table]: if f: try: arcpy.Delete_management(f) except: pass
Note - we don't need to clean up lyrName because it's just a simple string object that will be deleted when the python script ends. The variable tmp_layer is assigned a result object returned from MakeFeatureLayer, but when you use it as input to a tool (like Delete_management) the tool is only passed the result object's string representation, which is just the string (above, "lyr201409015110231", or, below, "lyrname") so we don't need to unpack it with result.getOutput(0).
Here are some details, shown from the Python prompt (in ArcMap). Gotta love it.
>>> lyr = arcpy.MakeFeatureLayer_management(r"temp.shp", "lyrname") >>> type(lyr) <class 'arcpy.arcobjects.arcobjects.Result'> >>> lyr <Result 'lyrname'> >>> str(lyr) 'lyrname' >>> lyr.getOutput(0) <map layer u'lyrname'> >>> arcpy.Delete_management(lyr) <Result 'true'> >>> print(arcpy.GetMessages()) Executing: Delete lyrname # Start Time: Mon Sep 15 11:32:05 2014 Succeeded at Mon Sep 15 11:32:05 2014 (Elapsed Time: 0.00 seconds)
When you create a layer or table view using geoprocessing tools, the new layer or table view is stored in an internal layer list, which is a different list from the ArcMap table of contents. This means that geoprocessing actually keeps two lists of layers and table views:The list of layers in the ArcMap table of contentsThe internal list of layers created by geoprocessing tools
def clearLayers(): mxd = arcpy.mapping.MapDocument('CURRENT') for df in arcpy.mapping.ListDataFrames(mxd): for lyr in arcpy.mapping.ListLayers(mxd, "", df): arcpy.mapping.RemoveLayer(df, lyr) del mxd
Los miembros registrados pueden publicar, seguir actualizaciones y más. ¿Nuevo aquí? Regístrate gratis.
Find useful guides, FAQs, and documents to help you navigate and make the most of Esri Community.