I have a python script in ArcGIS 10.1 which takes in a few inputs from the user. One of the inputs is a coordinate system. I would like to test whether the coordinate system the user chose was projected or geographic.
A sample of the code is:
input1 = arcpy.GetParameterAsText(0)
input2 = arcpy.GetParameterAsText(1)
coordsys = arcpy.GetParameterAsText(2)
desc1 = arcpy.Describe(input1)
desc2 = arcpy.Describe(input2)
descCoordSys = arcpy.Describe(coordsys)
The code runs fine until the last line.
I have forced the user to enter a coordinate system in the third line:
What am I missing here?
EDIT:
I've tried to implement the changes proposed by @dmahr but it still doesn't work. It isn't getting to the nested try
statement. It just quits with the error "There was an error with an input file. Please run again." I'm not sure what I'm doing wrong. I've tried with both projected and geographic coordinate systems.
input1 = arcpy.GetParameterAsText(0)
input2 = arcpy.GetParameterAsText(1)
coordsys = arcpy.GetParameter(2)
try:
desc1 = arcpy.Describe(input1)
desc2 = arcpy.Describe(input2)
try:
coordsys_linearunit = coordsys.linearUnitName
except:
arcpy.AddError("Input coordinate system is not projected.")
sys.exit("Exiting.")
except:
arcpy.AddError("There was an error with an input file. Please run again.")
sys.exit("Exiting.")
Answer
Two possible solutions I've found in playing around with the SpatialReference
class:
In your script tool parameter's dialog, change the data type of the Coordinate System parameter to Spatial Reference. A spatial reference contains a bit more information than a coordinate system and is what is expected by
GetParameter
if you're expecting it to create aSpatialReference
object.- Note: In my testing this only works when run as a script tool, not as a standalone Python script, presumably because
GetParameter
requires the script tool parameter definitions to infer what type of object to create from the input string.
- Note: In my testing this only works when run as a script tool, not as a standalone Python script, presumably because
In addition to the above change, you can use the
SpatialReference.loadFromString()
method to create a spatial reference object from its string representation explicitly. This should work both within a script tool and a standalone Python script. E.g.:import arcpy
input1 = arcpy.GetParameterAsText(0)
input2 = arcpy.GetParameterAsText(1)
srtxt = arcpy.GetParameterAsText(2)
sr = arcpy.SpatialReference()
sr.loadFromString(srtxt)
if not sr.type == "Projected":
raise RuntimeError("Input coordinate system is not projected.")You'll note I also changed the coordinate system type checking to be more explicit and changed the error handling logic to raise an error which is a bit more Pythonic, though you are free to handle it how you want.
No comments:
Post a Comment