Presentation is loading. Please wait.

Presentation is loading. Please wait.

This lecture Introduction to arcpy Debugging Using arcpy.

Similar presentations


Presentation on theme: "This lecture Introduction to arcpy Debugging Using arcpy."— Presentation transcript:

1 This lecture Introduction to arcpy Debugging Using arcpy

2 Arc env variables arcpy.env.workspace = "c:/data/myGeodatabase.gdb"
arcpy.env contains a set of variables that control overall behaviour in Arc. arcpy.env.workspace = "c:/data/myGeodatabase.gdb" From then on, this is default location for output. List all: environments = arcpy.ListEnvironments() for environment in environments: env_value = getattr(arcpy.env, environment) Reset all env settings: arcpy.ResetEnvironments() Reset an env setting: arcpy.ClearEnvironment("workspace")

3 Scratch space arcpy.env.scratchGDB and scratchFolder used for temp files. Set through the scratchWorkspace: arcpy.env.scratchWorkspace = 'c:/LandUse/scratch.gdb' arcpy.env.scratchWorkspace = 'c:/LandUse' If workspace is set to a GDB or folder, the other adjusts appropriately, with the default database being scratch.gdb. Can generate temp paths for use in tools, thus: temp_path = arcpy.CreateScratchName(workspace=arcpy.env.scratchGDB)

4 Other useful env variables
arcpy.env.addOutputsToMap == True | False arcpy.env.autoCommit == True | False arcpy.env.overwriteOutput == True | False arcpy.env.extent = arcpy.Extent(-107.0, 38.0, , 40.0) Some tools will only process features within the current extent.

5 Built in functions: Exists
Checks whether something exists. a = arcpy.Exists("c:/data/buildings.shp") Note that the advantage of doing this in Arc is that it unifies multiple files (for example the various files that make up a full shapefile with data) to a single entity, and allows path-based exploration of geodatabases (so called catalog paths as opposed to system paths): a = arcpy.Exists("c:/data/myGeodatabase.gdb/roads") We'll see more built in functions when we look at data, but as a start here's two.

6 Checking inputs For scripts, the system should check input parameters exist. Otherwise you can check with: input = arcpy.GetParameterAsText(0) if arcpy.Exists(input):

7 Built in functions: Walk
Walk(top, topdown, onerror, followlinks, datatype, type) allows scanning of a directory tree in Arc file space including geodatabases, e.g.: c:\data\MyGeoDataBase.gdb\myfeaturedataset\myfeatureclass for dirpath, dirnames, filenames in arcpy.da.Walk( workspace, topdown=True, datatype="RasterDataset"): if "back_up" in dirnames: dirnames.remove('back_up') for filename in filenames: rasters.append(os.path.join(dirpath, filename)) Followlinks is for online databases. Types listed at:

8 Built in functions: Describe
Function returns a Describe object particular to the data type passed in. A bit like a uber-"type()". Can contain "Property sets" which can be drilled into further. d = arcpy.Describe("c:/data/buildings") f = d.FieldInfo print(f.count) (for this example, see also ListFields and ListIndexes)

9 Geoprocessing tools Essentially the tools presented in ArcToolbox. Need to find the proper name of the toolbox and tool (we'll see how in practicals). You can then do: arcpy.toolname_toolboxname(params) or arcpy.toolboxname.toolname(params) In which case it will quietly run. If you want associated parameter dialogs in an addin: pythonaddins.GPToolDialog(toolboxname, toolname) But, as we'll see in the practicals, there are some issues with this.

10 Geoprocessing tools Inputs in [] indicate a list should be used.
Will also generally take semicolon separated strings and a ValueTable:

11 Geoprocessing tools For a custom toolbox in an external script, you need to load the toolbox to use it (as you'd have to as a user): arcpy.ImportToolbox(toolbox_path, alias_for_toolbox) The alias is a short (singleword) name for the toolbox to use in, e.g. arcpy.toolname_toolboxname(params) as the toolboxname. The alias_for_toolbox is optional if the toolbox has an alias set manually.

12 Using extensions If tools are in Arc extension packs (not application extension addins), you need to deal with the licensing: For example: import arcpy.sa arcpy.CheckOutExtension("spatial") # do stuff arcpy.CheckInExtension("spatial") Here we're assuming the license is ok. To check licences: if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") List of extension names at: See also: extensions.htm

13 Finding tools Search window in Arc (we'll see how to add tools to this in the practicals). tools = arcpy.ListTools("*") tools = arcpy.ListTools("*_conversion") Note optional wildcard * for tool in tools: print(arcpy.Usage(tool)) for toolbox in arcpy.ListToolboxes(): print(toolbox)

14 Optional tool parameters
Fill in spaces with "", "#" (including quotes), or None. Use kwargs. For tools that demand an output path, missing out the output/setting it to "#" or None will usually make the tool result a system-created temp file. This saves having to determine this beforehand, but requires write access to default locations.

15 GUI options We've seen that scripts and models can have parameter GUIs. Addins are explicitly GUI elements, but can spawn others (filedialogs and messages, for example). You can add a tool to buttons and menus from a custom toolbox using the customisation options. The tool should be listed under "Geoprocessing". If not, you can add it manually: removing-tools-on-menus-and-toolbars.htm

16 Tool results Come back as a "Result" object. Usually path to output, or single data value or a list of data, including lists of lists for multivalue parameters. result = arcpy.Buffer_analysis("bomb", "buffer", "100 METERS") print (result) For multiples: result.outputCount result.getOutput(i) # Returns strings, recordsets or layers. result[i] # The same. result.saveToFile("c:\temp\file.rlt")

17 Result result.status gives info: 0 : New 1 : Submitted 2 : Waiting 3 : Executing 4 : Succeeded 5 : Failed 6 : Timed out 7 : Cancelling 8 : Cancelled 9 : Deleting 10 : Deleted for i in range(result.messageCount): print (result.getMessage(i)) Last is often the most useful: print(result.GetMessage(result.GetMessageCount - 1)) Alternatively: print(result.GetMessages()) However, because there are cases where tool failure doesn't create a results object, you can also do the same with arcpy directly: print(arcpy.GetMessages())

18 Online services Some tools can run online services.
IsSynchronous can be used to see if the tool is asynchronous (i.e. results may not be immediate and the code can continue to run). results = arcpy.Buffer_analysis(bomb, output, "100 METERS", "FULL", "ROUND", "NONE") if not arcpy.IsSynchronous("Buffer"): while results.status < 4: time.sleep(0.1) Note just toolname used. Example of getting a map image from a server: See also examples for recreating results at:


Download ppt "This lecture Introduction to arcpy Debugging Using arcpy."

Similar presentations


Ads by Google