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.
mxd = arcpy.mapping.MapDocument("CURRENT")
Layer2 = arcpy.mapping.ListLayers(mxd, "USA City Populations")
df = arcpy.mapping.ListDataFrames(mxd)
arcpy.env.extent = df.extent
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.