How a script can work within a map document python interpreter but fail as a standalone script has puzzled me several times and I usually find a way to work around it. This one though I want answers to.
I have simplified a part of a much larger script to indicate the issue I am having, all I want to do is select all the features within the current map extent(I need a count of them, so I use this with GetCount). Since Select By Attribute works with the Extent Environmental variable, I figured that was the easiest way to do it. When running with the python interpreter in a map document, this script works fine.
import arcpy mxd = arcpy.mapping.MapDocument("CURRENT") Layer2 = arcpy.mapping.ListLayers(mxd, "USA City Populations") df = arcpy.mapping.ListDataFrames(mxd) arcpy.env.extent = df.extent arcpy.SelectLayerByAttribute_management(Layer2)
It select all the features in my dataframe extent as I want. However, I want to run this as a standalone, only changing the mxd to the file path of the map document instead of the "CURRENT" key word it fails.
ExecuteError: ERROR 000358: Invalid expression
Failed to execute (SelectLayerByAttribute).
Select By Attribute is supposed to be able to work with TOC Layers, so I don't see why there is an issue using a Layer Object. I've also attempted this with the Layer Name as it appears in the TOC hard-coded in as the input for SelectLayerByAttribute. Again this works fine when run within the map document with the python interpreter and using the "CURRENT" Keyword but fails as a standalone with the map document path hard coded in. I know the workaround is just to make a Feature Layer, but I want to understand why this simple code won't work standalone but will within the python interpreter.
Solved! Go to Solution.
if it is totally offline, I am not sure why you would want to work with a dataframe. In any event, an in arcmap can become a *.lyr for use out of arcmap, it references the data and contains the symbology
It is part of a larger script that will eventually export the map to a pdf. I need to get the count of the features in the current map extent for that layer then change the definition query depending on the count.
What version are you running? I am running 10.5, and I just tried to recreate your problem using an MXD and I could not. I am not sure if I didn't set everything up the same as you or if something else is going on.
Does you map layer have a definition query? What type of data store is the layer in, file geodatabase?