Python Scripting for ArcGIS - Paul and ArcGIS • PhPython is the prefdferred scriiipting language...

download Python Scripting for ArcGIS - Paul and ArcGIS • PhPython is the prefdferred scriiipting language for AGISArcGIS 1. You can run Python from within ArcGIS – Python Window works like

of 118

  • date post

    14-May-2018
  • Category

    Documents

  • view

    216
  • download

    1

Embed Size (px)

Transcript of Python Scripting for ArcGIS - Paul and ArcGIS • PhPython is the prefdferred scriiipting language...

  • PythonScriptingforArcGIS

    PaulZandbergenDepartmentofGeographyp g p yUniversityofNewMexico

  • Outline of TopicsOutlineofTopicsd Introduction

    Examples,PythonandArcGIS,Pythonversions Fundamentals of geoprocessing in ArcGISFundamentalsofgeoprocessing inArcGIS Pythonlanguagefundamentals

    WheretorunPythoncode Datatypes:numbers,strings,lists Functionsandmodules Controllingworkflowg

    ArcPy:Geoprocessing usingPython Usingtools,functions,classes

    b d l d k h l Describingdata,listingdata,workingwithlists Creatingcustomtools

    Scripttools,toolparametersp , p Resources

  • Workshop Materials PostedWorkshopMaterialsPosted

    posted until October 24

    h // l db / k h

    posteduntilOctober24

    http://www.paulzandbergen.com/workshops

  • Forthcoming BookForthcomingBook

    PythonScriptingforArcGIS Esri PressEsri Press Sometimein2012 UpdatedforArcGIS 10.1

    Sampleexercisesposted(for10.0)

  • Introduction

  • Prior Knowledge and ExperiencePriorKnowledgeandExperience

    UsingArcGIS 9.3or10.0? Workshopisfor10.0p

    PriorPythonexperience? Imnotassuminganyg y

    O h i i ? Otherprogrammingexperience? Imnotassumingany

  • Example 1Example1

    Scripttocopyallshapefiles inafolderintoageodatabase

    import arcpyfrom arcpy import envenv.overwriteOutput = True

    k " / k h / 01"env.workspace = "c:/workshop/ex01"fclist = arcpy.ListFeatureClasses()for fc in fclist:

    fcdesc = arcpy.Describe(fc)py ( )arcpy.CopyFeatures_management(fc, "c:/workshop/ex01/study.mdb/"

    + fcdesc.basename)

  • Example 2Example2

    Scripttooltogenerateaknearestneighbortable RunsanexistingArcGIS toolmultipletimes,writestheresult

    import arcpyfrom arcpy import env

    it t t Tenv.overwriteoutput = Trueinfc = arcpy.GetParameterAsText(0)output = arcpy.GetParameterAsText(1)k = arcpy GetParameter(2)k = arcpy.GetParameter(2)n = 1f = open(output, "w")while n

  • Example 3Example3

    ScripttooltorunHuffmodel SophisticatedanalysisnotavailableinArcGIS

  • Example 3Example3

  • What is Python Scripting?WhatisPythonScripting?

    Add f i li A GIS AddfunctionalitytoArcGIS IntegratedintoArcGIS interfaceB ild i i f i li Buildsuponexistingfunctionality

    AutomatesrepetitivetasksExpands analysis options Expandsanalysisoptions

    Sh f ti lit Sharenewfunctionality ScripttoolsworkjustlikeregulartoolsC b i t t d i t d l t l Canbeintegratedintomodels,tools

    Easytosharewithothers(free)

  • Why Python?WhyPython?

    Free,opensource Objectoriented BasicscriptingANDcomplexobjectorientedprogramming Batteriesincluded Embracedbygeospatialcommunity,includingESRI Manylibraries

  • Python CommunityPythonCommunity

    http://www.python.org

  • Python and ArcGISPythonandArcGIS

    P h i h f d i i l f A GIS PythonisthepreferredscriptinglanguageforArcGIS

    1. YoucanrunPythonfromwithinArcGIS PythonWindowworkslikeaninteractiveinterpreter

    2. AlltoolsinArcToolbox canbeaccessedfromPython ImportArcPy togetfulllibraryoftools

    3 P th i t b d i t t l3. Pythonscriptscanbemadeintotools ExtendfunctionalityofArcGIS

    4 Support for other scripting languages will go away4. Supportforotherscriptinglanguageswillgoaway VBScriptandJScript beingreplacedbyPython

  • Python Versions and ArcGISPythonVersionsandArcGIS

    Versions: CurrentversionofPythonis3.2.2

    Python that works with ArcGIS 10 0 is 2 6 x PythonthatworkswithArcGIS 10.0is2.6.x PythonthatworkswithArcGIS 10.1is2.7.x MovetoPython3.xlikelyonlywithArcGIS 11y y y

    ArcGIS onlyworkswithaspecificversionofPython:y p y UsetheonethatcomesinstalledwithArcGIS DontinstallyourownversionofPython

  • Installing PythonInstallingPython

    RemoveanyexistinginstallationsofPython InstallArcGIS 10.0

    Python2.6.5willbeinstalledbydefault Install a Python editorInstallaPythoneditor ConfiguretheeditortoworkwithArcGIS

    Note:YoucanrundifferentversionsofPythonononemachine however,acleaninstallofPython2.6.5withArcGIS 10.0isrecommended

  • Demo:CheckArcGIS andPythoninstallation

  • Fundamentals of GeoprocessingFundamentalsofGeoprocessinginArcGIS

  • Geoprocessing ToolsGeoprocessing Tools

  • Tool OrganizationToolOrganization

  • Tool DialogsToolDialogs

  • Tool ParametersToolParameters

    Parameters Requiredq Optional

    Errors Warning

  • Environment SettingsEnvironmentSettings

  • Geoprocessing OptionsGeoprocessing Options

  • Demo:Geoprocessing Fundamentals

  • RunningPythonCode

  • Two ways to run Python CodeTwowaystorunPythonCode

    1. UsinganInteractiveInterpreter Codeisexecuteddirectlylinebyliney y

    2 B i i t2. Byrunningascript Codesavedina.py file RunfromwithinaPythoneditorordirectlyfrom

    operatingsystemp g y

  • Where to type and run Python code?WheretotypeandrunPythoncode?

    1. PythonwindowinArcGIS BuiltintoanyArcGIS Desktopapplication Goodfortestingcode,veryshortscripts

    2. Pythoneditor IDLE installed by defaultIDLEinstalledbydefault Manyothers,PythonWin isagoodonetostart Good for more complex code saving scripts Goodformorecomplexcode,savingscripts

  • Python Window in ArcGISPythonWindowinArcGIS

  • Python Window in ArcGISPythonWindowinArcGIS

    Workswithcurrentmapdocument Interactiveinterpreter:

    Executescodedirectlylinebyline Good for testing short codeGoodfortestingshortcode CodecanbesavedN h ki / d b i Noerrorchecking/debugging

  • Python Editor IDLEPythonEditor IDLE

  • Python Editor PythonWinPythonEditor PythonWin

  • Python EditorPythonEditor

    Standalone outsideofArcGIS Interactive interpreter:Interactiveinterpreter:

    Executescodedirectlylinebyline( ) Savecodeasscriptfiles(.py)

    Good for organizing more complex codeGoodfororganizingmorecomplexcode

  • Demo:RunningsimplePythoncode

  • PythonDocumentation

  • Python DocumentationPythonDocumentation

    http://www.python.org

  • Python DocumentationPythonDocumentationVersionspecific!p

    http://docs.python.org

  • Python Beginners GuidePythonBeginnersGuide

    http://wiki.python.org/moin/BeginnersGuide

  • Python BooksPythonBooksVersion specific!Versionspecific!

    N f th b k i l di thi A GIS i !NoneofthesebooksincludinganythingonArcGIS orgeoprocessing!

  • PythonLanguageFundamentals

  • Python Data TypesPythonDataTypes

    Number(integerandfloat) String List Tuple Dictionary

    Strings,listsandtuples aresequences Strings,numbersandtuples areimmutable Listanddictionariesaremutable

  • NumbersNumbers

    Integers Wholenumber,i.e.nodecimals e.g.34

    Floats Decimalpoint e.g.34.8307g

  • Numerical OperatorsNumericalOperators

    Operator Description Integer FloatingpointExample Result Example Result

    * Multiplication 9*2 18 9*2.0 18.0/%+

    DivisionModulusAddition

    9/29%29+2

    4111

    9/2.09%2.09+2.0

    4.51.011.0

    Subtraction 9 2 7 9 2.0 7.0

  • Demo:NumericalOperators

  • StringsStrings

    Asetofcharacterssurroundedbyquotesiscalledastringliteral

    Tocreateastringvariable,assignastringliteraltoit

    >>> mytext = "Crime hotspot maps are cool.">>> print mytext>>> print mytextCrime hotspot maps are cool.

  • Quotes in PythonQuotesinPython

    InPythonsingleanddoublequotesarethesame "NIJ" isthesameas'NIJ'

    >>> print "I said: 'Let's go!'">>> print I said: Let s go!

    QuotesinPythonarestraightup "text" or 'text', nottext ortext

    Be aware of copy/paste and autoformattingBeawareofcopy/pasteandautoformatting

  • VariablesVariables

    Pythonscriptsusevariables tostoreinformation Toworkwithvariablesuseanassignment statement

    >>> x = 17>>> x 17>>> x * 234

  • VariablesVariablesP h d i i Pythonusesdynamic assignment

    >>> x 17>>> x = 17>>> type(x)

    >>> x = "GIS">>> type(x)>>> type(x)

    Noneedtodeclarevariables Valuedefinesthetype

  • Variable NamesVariableNames

    Rules Letters,digitsandunderscores Cannotstartwithadigit Dontusekeywords(print,import,etc.)

    RecommendationsRecommendations Bedescriptive(count insteadofc) Keep it short (count instead of count of records)Keepitshort(count insteadofcount_of_records) Followconvention:alllowercase,useunderscores

  • Statement and ExpressionsStatementandExpressions

    APythonexpression isavalue

    >>> 2 * 173434

    APythonstatement isaninstructiontodosomething

    >>> x = 2 * 17

  • Working with StringsWorkingwithStrings

    Concatenatestrings

    >>> x = "G">>> y = "I">>> y I >>> z = "S">>> print x + y + zGIS

  • Converting to StringConvertingtoString100>>> temp = 100

    >>> print "The temperature is " + temp + " degrees"TypeError: cannot concatenate 'str' and 'int' objectsTypeError: cannot concatenate str and int objects

    >>print "The temperature is " + str(temp) + " degrees"

    Convertingthevalueofavariablefromonetypetoanotherisknownascasting

  • ListsLists

    APythonlistisanorderedsetofitems Thelistofitemsissurroundedbysquarebrackets[],andthe

    it t d b ( )itemsareseparatedbycommas(,) Itemscanconsistofnumbers,stringsandotherdatatypes

    mylist = [1, 2, 4, 8, 16, 32]j imywords ["jpg", "bmp", "tif"]

    Listsareverywidelyusedingeoprocessing: e.g.listoffeatureclasses,listofrecords,listoffields,etc.

  • Python Funct