Hot answers tagged

71

I believe that the user should clearly define their objectives before deciding which set of tools to use. ModelBuilder and Python scripting excel at different tasks. A few thoughts: ModelBuilder has no mapping capabilities, whereas arcpy.mapping does. Python can be used to optimize workflows, such as with the multiprocessing package or with parallel ...


53

I compiled this list a while ago so it may be somewhat out of date. Making it community wiki so anyone can update/correct/add to it. Also see these general tips for new Python programmers in this answer. Presentations: Python Scripting for ArcGIS Getting Started with Python in ArcGIS 10 ArcGIS Geoprocessing: Python Scripting – Advanced Techniques Python ...


49

Although this question was already answered, I thought I could chime in an give my two cents. DISCLAIMER: I worked for ESRI at the GeoDatabase team for some years and was in charge of maintaining various parts of GeoDatabase code (Versioning, Cursors, EditSessions, History, Relationship Classes, etc etc). I think the biggest source of performance problems ...


39

I am using an example with 1 million randomly generated points inside of a filegeodatabase. Attached here. Here is some code to get us started: import time import arcpy arcpy.env.workspace = "C:\CountTest.gdb" time.sleep(5) # Let the cpu/ram calm before proceeding! """Method 1""" StartTime = time.clock() with arcpy.da.SearchCursor("RandomPoints", ...


31

Usually Python debuggers/IDEs assume the Python script is running in the same process as itself so debugging a script running in ArcMap.exe is right out -- you need to get enough of the GP scripting environment bootstrapped in a Python script as you can to debug with. A method that's worked very well for me over the past few years is to write a simple ...


27

General python optimization techniques can save you substantial amounts of time. One really good technique for getting a lowdown of where the hold ups are in your script is using the built-in cProfile module: from cProfile import run run("code") # replace code with your code or function Testing using a small data sample will allow you to pinpoint which ...


26

This routine for arcgis10 returns all fcs (standalone OR within a feature dataset) inside a gdb. Just set your arcpy.env.workspace then do a for loop def listFcsInGDB(): ''' set your arcpy.env.workspace to a gdb before calling ''' for fds in arcpy.ListDatasets('','feature') + ['']: for fc in arcpy.ListFeatureClasses('','',fds): ...


26

You can do this using a cursor to grab the data from your table and write to a comma-delimited text file. EDIT: I'm adding a more concise block of code to accomplish the task using the csv module of Python New Answer using arcpy.da cursor: import arcpy,csv table =r'c:\path\to\table' outfile = r'c:\path\to\output\ascii\text\file' #--first lets make a ...


26

If an Esri well-known ID is below 32767, it corresponds to the EPSG ID. WKIDs that are 32767 or above are Esri-defined. Either the object isn't in the EPSG Geodetic Parameter Dataset yet, or it probably won't be added. If an object is later added to the EPSG Dataset, Esri will update the WKID to match the EPSG one, but the previous value will still work. ...


26

Use the following method on the Result object and you'll be able to cast as int: .getOutput(0) will return the value at the first index position of a tool. int(arcpy.GetCount_management(Path_Pts).getOutput(0))


25

It seems the most common problem with these types of "flow maps" is that when many lines are included, they collide to such a great extent that it makes it difficult to discern any non-obvious pattern (when reciprocal flows are considered it happens to an even greater extent). Also the long lines tend to dominate the graphic, although it is quite possible ...


24

Keep in mind that Arcpy is essentially a wrapper around ArcObjects. But if you're just trying to call some Python scripts that you don't want to have to rewrite you can spawn a process that calls the python executable with your args. var startInfo = new ProcessStartInfo() { CreateNoWindow = false, UseShellExecute = false, FileName = ...


24

Any time you have a selection on a layer a cursor object will only return the selected rows. for row in arcpy.SearchCursor("name_of_layer_with_selection"): print row.field1, row.field2


24

The two are very, very close in functionality but not completely equivalent. Common to both Includes a set of tools with a unique alias for identification Can call from arcpy Get a Geoprocessing tool dialog (essentially a full UI) for free for each tool Can keep all Python code in one file (embedding tool source in TBX, holding all the implementation in ...


24

It doesn't work because you haven't called the Xlrd modules to read the Excel spreadsheet. Implement it something like this: import xlrd workbook = xlrd.open_workbook('my_workbook.xls') worksheet = workbook.sheet_by_name('Sheet1') This will allow you to read an XLS file with Python. However, ArcPy will read XLS without Xlrd. You can consider the Excel ...


23

If you're looking for an ArcObjects way to get it, then How to programmatically determine the size of a feature class in a file geodatabase? will provide that -- otherwise, you can enable the Size column in the Customize menu -> ArcCatalog Options -> Contents tab: This works on file geodatabases but not on SDE geodatabases (in that case you could use ...


23

I've been using "in_memory" quite a bit recently. It can be very useful, as it has the potential to dramatically increase processing speeds for certain tasks, however if you are working with very large datasets, it might cause your program to crash. You can use "in_memory" to define process outputs... often, if I am performing a task on a feature class, ...


23

I would probably just put it in GitHub until you really know what you want to share. Even ESRI started jumping on this bandwagon after GeoIQ acquisition.


22

You can change it from the GP options dialog, just point to your executable of choice for editor/debugger.


22

EDIT: 2015 Solution My solution now is to use a small module which goes off and hunts for ArcGIS on your PC. Once find it adds the correct paths to the environment so that you can import arcpy. The usage goes like this: try: import archook #The module which locates arcgis archook.get_arcpy() import arcpy except ImportError: # do whatever ...


21

A couple potential suggestions to help speed up your process are: Select Layer By Attribute can be in a Python-only script, without ever launching ArcGIS Desktop. You need to convert your "buff" reference from a file-based reference to an "ArcGIS layer" reference, which ArcGIS can process selection queries against. Use ...


21

One of the developers of arcpy.da here. We got the performance where it is because performance was our primary concern: the main gripe with the old cursors were that they were slow, not that they lacked any particular functionality. The code uses the same underlying ArcObjects available in ArcGIS since 8.x (the CPython implementation of the search cursor, ...


20

I would question the need to use your own GUI for Geoprocessing. The idea of a geoprocessing tool is that it goes through the standard interfaces (the GP progress dialog if enabled for messages and a progress dialog, the GP tool dialog for setting parameters and running the tool, etc) and I'd like to hear the use case for trying to circumvent that all. ...


20

The Polyline class has a new method called "positionAlongLine" in ArcGIS 10.1. This will return a PointGeometry object with exactly one point at a specified distance from the starting end of the line, or a fraction of the distance between the start and end. To find the midpoint, you would just need to do positionAlongLine(0.5,True). To find the midpoints for ...


19

So, I wrestled with this exact same problem for quite a while. Here's what I found to work: import arcpy from arcpy import env # get the map document mxd = arcpy.mapping.MapDocument("CURRENT") # get the data frame df = arcpy.mapping.ListDataFrames(mxd,"*")[0] # create a new layer newlayer = arcpy.mapping.Layer(path_to_shapefile_or_feature_class) # add ...


19

I've set this up as a ArcToolbox type of script, rather than field calculator as whuber did. This is pretty much a straight port of whubers Avenue code. EDIT: the script assumes the height is stored in a field in the featureclass attribute table, not a featureclass with 3D geometries (PolygonZ) import arcpy,os,math arcpy.env.overwriteOutput=True ...


19

Here is a Python script for ArcGIS 10 that basically does what you want, except that the output is a CSV file, not a geodatabase table. Feel free to modify and use as you like. Note that it is not well tested and not supported, so use at your own risk. """ This script looks through the specified geodatabase and reports the names of all data elements, their ...


19

If you are working solely within the confines of ArcGIS, there are a few considerations I would consider when attempting to determine the approach to take. What are you trying to accomplish, What are your current skill sets, Will you be sharing your work with others to use, learn from, or manipulate, and Who is your intended audience. Given those ...


19

Yes, it is possible. Before you can add a feature class you need to turn it into a feature layer. This arcpy code should help: import arcpy FC = r"C:\...\featureclass" arcpy.MakeFeatureLayer_management(FC, "nameoffeatureclass") MXD = arcpy.mapping.MapDocument(r"C:\...\your.mxd") DF = arcpy.mapping.ListDataFrames(MXD)[0] layer = ...


19

I'm not aware of anything in the arcpy API that will do the scaling for you, but writing a function to do so would be relatively simple. The code below does the scaling for 2D features, and doesn't take into account M or Z values: import arcpy import math def scale_geom(geom, scale, reference=None): """Returns geom scaled to scale %""" if geom ...



Only top voted, non community-wiki answers of a minimum length are eligible