I am trying to use the script from Randomly subsetting X% of selected points using ArcPy? to randomly select and export points in ArcGIS.
Specifically, I am using this:
def SelectRandomByCount (layer, count):
import random
layerCount = int (arcpy.GetCount_management (layer).getOutput (0))
if layerCount < count:
print "input count is greater than layer count"
return
oids = [oid for oid, in arcpy.da.SearchCursor (layer, "OID@")]
oidFldName = arcpy.Describe (layer).OIDFieldName
delimOidFld = arcpy.AddFieldDelimiters (layer, oidFldName)
randOids = random.sample (oids, count)
oidsStr = ", ".join (map (str, randOids))
sql = "{0} IN ({1})".format (delimOidFld, oidsStr)
arcpy.SelectLayerByAttribute_management (layer, "", sql)
arcpy.CopyFeatures_management(layer, "random_start_20pop")
arcpy.SelectLayerByAttribute_management(layer, "SWITCH_SELECTION")
arcpy.CopyFeatures_management(layer, "endings_for_20pop")
What should I do to create Python tool in ArcToolbox instead of pasting it to the Python window? I've tried already to save it in toolbox as a script but I assume that I did it wrong. I tried to proceed as it is shown here Adding a script tool
Best Answer
To use this function inside a Python Toolbox in ArcMap:
Define the toolbox parameters. (http://pro.arcgis.com/en/pro-app/arcpy/geoprocessing_and_python/defining-parameter-data-types-in-a-python-toolbox.htm. For example:
def getParameterInfo(self):
Get the parameters and call the function. For example:
def execute(self, parameters, messages): inputlayer = parameters[0].valueAsText outputgdb = parameters[1].valueAsText number = parameters[2].valueAsText self.SelectRandomByCount(inputlayer, number, outputgdb)
Of course, you would have to modify it a bit to suite your needs. This code is mostly an example of how to proceed.