5

I am trying to write a python script and am stuck on the first obstacle.

I want the user to select features in ArcMap and then use these selected features in a python script.

Is that at all possible and does someone have a code example?

The code that I have now uses all the features instead of just the selected ones. Please see code snippet below.

arcpy.MakeFeatureLayer_management(pipes,"pipeslyr")
arcpy.SetParameter(0,"pipeslyr")
pipesnew = os.path.join(ws,"pipesnew")

arcpy.CopyFeatures_management("pipeslyr", pipesnew)
PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Kat
  • 265
  • 1
  • 3
  • 11

2 Answers2

9

arcpy.CopyFeatures_management works like right-clicking on the layer > export data > selected features. Then you can make the layer from that exported selection. I'd do this "in_memory" so you don't have deal with overwriting each time you run the script.

import arcpy
from arcpy import env

arcpy.env.workspace = "in_memory"

selected_features = "The Feature Class with the selection.shp"
pipes = "the new feature class to convert to a layer"

#this will create a new feature class from the selected features but will do it In Memory
arcpy.CopyFeatures_management (selected_features, pipes)

#Now do all the other stuff you want like convert it to a layer and work with it

arcpy.MakeFeatureLayer_management(pipes,"pipeslyr")

The selection would need to be made before this is run.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Pete
  • 622
  • 1
  • 6
  • 20
1

As your script stands if you want to copy out a selection then the selection must exist on the layer, but you would need to get a handle on the layer from your mxd first. Have a look at this Getting started with arcpy.mapping tutorial page about referencing a layer in an mxd.

PolyGeo
  • 65,136
  • 29
  • 109
  • 338
Hornbydd
  • 43,380
  • 5
  • 41
  • 81