I am running a python script from within ArcMap 10.5 and have always noticed that when I need to rerun the script in the same session, I get either an error or python goes to the next line showing just a ">>>". This happens more often on successful runs, but if the script fails because of syntax or data source issue, I can rerun it and it'll be fine. I often have to close out of my MXD and reopen it in order to run the script. It seems when it runs successfully, that there is something left open or the cache needs to be cleared in order for it to run again.
The errors that I get are random and are simply solved by closing the MXD and reopening.
Is there a way that I can clear the cache or force Arc to stop all background processes (if any are running) in Python?
import arcpy
from State_Dictionary import st_list_tup
# DEFINE VARIABLES
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
lyr5 = arcpy.mapping.Layer("Counties")
lyr2 = arcpy.mapping.Layer("Otolaryngologists to Primary Care Physicians")
lyr3 = arcpy.mapping.Layer("Otolaryngologists")
for County in arcpy.mapping.ListLayers(mxd):
if County.name == "Counties":
lyr5 = County
for layer in arcpy.mapping.ListLayers(mxd):
if layer.name == "Otolaryngologists to Primary Care Physicians":
lyr2 = layer
if layer.name == "Otolaryngologists":
lyr3 = layer
st_abbr = "STATE_ABBR = '{}'"
Automate = "Auto_State = '{}'"
count_lyr = "STATE_NAME = '{}'"
for layer in arcpy.mapping.ListLayers(mxd)[0:13]:
lyr2.visible = False
lyr3.visible = False
for state, fname in st_list_tup:
layer.visible = True
layer.definitionQuery = Automate.format(state)
# CREATE SELECTION LAYER AND WHERE CLAUSE
arcpy.SelectLayerByAttribute_management(County,"NEW_SELECTION", count_lyr.format(fname))
# ZOOM TO STATE SELECTION THEN CLEAR SELECTION
df.zoomToSelectedFeatures()
# CLEAR SELCTION
arcpy.SelectLayerByAttribute_management(County, "CLEAR_SELECTION")
# DEFINITION QUERIES
lyr5.definitionQuery = count_lyr.format(fname)
print lyr2.definitionQuery, lyr3.definitionQuery, lyr4.definitionQuery
# UPDATE MAP ELEMENTS
for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
if elm.name == "Title":
elm.text = "{}".format(layer)
for elm in arcpy.mapping.ListLayoutElements(mxd, "TEXT_ELEMENT"):
if elm.name == "Subtitle":
elm.text = "{}".format(fname)
# EXPORT MAP SELECTION TO PNG IMAGE
arcpy.mapping.ExportToPDF(mxd, r"C:\Data Projects\AMA (43.1GB)\Map Automation\Practice Maps\{}\{} {}.pdf".format(fname, fname, layer))
# CLEAR DEFINITION QUERIES AND UPDATE MAP VIEW
arcpy.RefreshActiveView()
# DELETE LOCAL VARIABLES
del mxd, df, lyr3, lyr2, lyr4, lyr5
print "Success!"