Introducing Python in ArcGIS.docx
《Introducing Python in ArcGIS.docx》由会员分享,可在线阅读,更多相关《Introducing Python in ArcGIS.docx(15页珍藏版)》请在冰豆网上搜索。
![Introducing Python in ArcGIS.docx](https://file1.bdocx.com/fileroot1/2023-1/2/dc15da53-da80-428f-9d79-fb524c805d61/dc15da53-da80-428f-9d79-fb524c805d611.gif)
IntroducingPythoninArcGIS
WhatisPython?
Pythonisalanguagethatisusedtoautomatecomputingtasksthroughprogramscalledscripts.Automationmakesworkeasier,faster,andmoreaccurate.ThisappliestoGISandmanyotherareasofcomputerscience.LearningPythonwillmakeyouamoreeffectiveGISanalyst,butPythonprogrammingisatechnicalskillthatcanbebeneficialtoyouevenoutsidethefieldofGIS.
Pythonisagoodlanguageforbeginningprogramming.Pythonisahigh-levellanguage,meaningyoudon’thavetounderstandthe“nutsandbolts”ofhowcomputersworkinordertouseit.Pythonsyntax(howthecodestatementsareconstructed)isrelativelysimpletoreadandunderstand.Finally,Pythonrequiresverylittleoverheadtogetaprogramupandrunning.
Pythonisanopen-sourcelanguageandthereisnofeetouseitordeployprogramswithit.PythoncanrunonWindows,Linux,andUnixoperatingsystems.
InArcGIS,Pythoncanbeusedforcoarse-grainedprogramming,meaningthatyoucanuseittoeasilyrungeoprocessingtoolssuchastheBuffertoolthatwejustworkedwith.Youcouldcodeallthebufferlogicyourself,usingmoredetailed,fine-grainedprogrammingwithArcObjects,butthiswouldbetimeconsumingandunnecessaryinmostscenarios;it’seasierjusttocalltheBuffertoolfromaPythonscriptusingonelineofcode.
IntroducingPythonusingthePythonwindowinArcGIS
ThebestwaytointroducePythonmaybetolookatalittlebitofcode.Let’staketheBuffertoolwhichyourecentlyranfromtheArcToolboxGUIandrunitintheArcGISPythonwindow.ThiswindowallowsyoutotypesimpleseriesofPythoncommandswithoutwritingfullpermanentscripts.ThePythonwindowisagreatwaytogetatasteofPython.
Thistime,we’llmakebuffersof15milesaroundthecities.
1.OpenArcMaptoanewemptymap.
2.Addtheus_cities.shpdatasetfromtheLesson1data.
3.OntheStandardtoolbar,clickthePythonwindowbutton
.Oncethewindowappears,dragitovertothesideorbottomofthescreentodockit.
4.TypethefollowinginthePythonwindow(Don'ttypethe>>>.ThesearejustincludedtoshowyouwherethenewlinesbegininthePythonwindow.)
5.>>>importarcpy
>>>arcpy.Buffer_analysis("us_cities","us_cities_buffered","15miles","","","ALL")
6.Zoominandexaminethebuffersthatwerecreated.
You’vejustrunyourfirstbitofPython.Youdon’thavetounderstandeverythingaboutthescriptnow,buthereareafewimportantthingstonote.
ThefirstlineofthescriptimportarcpytellsthePythoninterpreter(whichwasinstalledwhenyouinstalledArcGIS)thatyou’regoingtoworkwithsomespecialscriptingabilitiesincludedwithArcGIS.You'llputthislineatthetopofallArcGIS-relatedcodethatyouwriteinthisclass.
Thesecondlineofthescriptactuallyrunsthetool.Youcantypearcpy,plusadot,plusanytoolnametorunatoolinPython.Noticeherethatyoualsoputanunderscorefollowedbythenameofthetoolboxthatincludesthebuffertool.Thisisnecessarybecausesometoolsindifferenttoolboxesactuallyhavethesamename(likeClip,whichisinboththeDataManagementandAnalysistoolboxes).
Afteryoutypedarcpy.Buffer_analysis,youtypedalltheparametersforthetool.Eachparameterwasseparatedbyacomma,andthewholelistofparameterswasenclosedinparenthesees.Getusedtothispattern,sinceyou'llfollowitwitheverytoolyouruninthiscourse.
Inthiscode,wealsosuppliedsomeoptionalparameters,leavingemptyquoteswherewewantedtotakethedefaultvalues,andtruncatingtheparameterlistatthefinaloptionalparameterwewantedtoset.
Howdoyouknowthesyntax,orstructure,oftheparameterstoenter?
Forexample,forthebufferdistance,shouldyouenter15MILES,‘15MILES’,15Miles,or’15Miles’?
ThebestwaytoanswerquestionsliketheseistoreturntotheGeoprocessingtoolreferencehelptopicfortheBuffertool.Allofthetopicsinthisreferencesectionhaveacommandlineusageandexamplesectiontohelpyouunderstandhowtostructuretheparameters.Alltherequiredparametersareshowninsidecarets(<>),whiletheoptionalparametersareshowninsidebraces({}).Fromtheexampleinthistopic,youcanseethatthebufferdistanceshouldbespecifiedas’15miles’.Becausethereisaspaceinthistext,orstring,youneedtosurrounditwithsinglequotes.
YoumighthavenoticedthatthePythonwindowhelpsyoubypoppingupdifferentoptionsyoucantypeforeachparameter.Thisiscalledautocompletion,anditcanbeveryhelpfulifyou'retryingtorunatoolforthefirsttimeandyoudon'tknowexactlyhowtotypetheparameters.WhenyouwritecodeinPythonWin,youdon'tgettheautocompletion,soyoumaywanttoreturntothePythonwindowfortipsasyoupracticewritinglinesofcode.IfyoucangetalineofcodetoworkinthePythonwindow,itwillprobablyworkinyourscriptthatyou'rewritinginPythonWin.
ThereareacoupleofdifferencesbetweenwritingcodeinthePythonwindowandwritingcodeinsomeotherprogram,suchasNotepadorPythonWin.InthePythonwindow,youcanreferencelayersinthemapdocumentbytheirnamesonly,insteadoftheirfilepaths.Thus,wewereabletotype"us_cities"insteadofsomethinglike"C:
\\data\\us_cities.shp".Wewerealsoabletomakeupthenameofanewlayer"us_cities_buffered"andgetitaddedtothemapbydefaultafterthecoderan.Ifyou'regoingtouseyourcodeoutsidethePythonwindow,makesureyouusethefullpaths.
Whenyouwritemorecomplexscripts,itwillbehelpfultouseanintegrateddevelopmentenvironment(IDE),meaningaprogramspecificallydesignedtohelpyouwriteandtestPythoncode.Laterinthiscoursewe’llexplorethePythonWinIDE.
InstallingPythonandPythonWin
IfyouinstalledthestudentversionofArcGIS,youshouldalreadyhavePythononyourcomputer.YoucanwritePythoncodeatanytimeinNotepadorothereditorsandsaveitasa.pyfile,butyouneedtohavePythoninstalledinorderforyourcomputertounderstandandruntheprogram.
Inthiscoursewe’llbeworkingwithPythonversion2.6,becauseArcGIS10.0onlyworkswiththatversion.IfyoudownloadPythonfromitshomepageatwww.python.org,you’llseethatthereareactuallyhigherversionsofPythonavailable.Pythonversions3andabovecontainsomebigchangesandaregoingtotakesometimeforthePythonusercommunitytoadopt.YoumayseesomeinformationaboutPython3inyourtextbookthatwillgiveyouanideaofthechangescominginthatversion.Youcanreadthisinformationifyou'reinterested,butit'snotapplicabletothiscourse.
PythoncomeswithasimpledefaulteditorcalledIDLE;inthiscourseyoucansimplyusetheIDLEinstalledautomaticallywithArcGIS,oryou’llusethePythonWinintegrateddevelopmentenvironment(IDE)tohelpyouwritecode.PythonWinisfree,hasbasicdebuggingcapabilities,andisincludedwithArcGIS.TheonlycatchisthatitisnotinstalledbydefaultwithArcGIS;youhavetodoitmanuallybyfollowingthesesteps.
1.InserttheArcGISEducationEditionDVDintoyourcomputer.
2.DismissanywelcomescreensthatappearandchooseStart>MyComputer(or“Computer”onWindowsVistaorWindows7).
3.FindyourDVDdrive,right-clickit,andclickOpen.YourgoalistogettothefolderstructureoftheDVD,notruntheAutoPlaythatshowstheESRIwelcomescreen.
4.Onceyou’vesuccessfullydisplayedthefolderstructure,opentheDesktopfolder.
5.OpenthePythonWinfolder.
7.Starttheinstallbylaunchingpywin32-210.win32-py2.6(orwhateverfileisnotthePythonWinreadmefile).IfyouareusingWindowsVistaorWindows7,right-clickthisfileandchooseRunasAdministratorand,whenprompted,choosetoAllowittorun.
8.ClickNextthroughthewizardtoinstallPythonWin.
9.PythonWindoesn'tputaWindowsshortcutanywhere,soyougettomakeoneyourself.Oncetheinstallcompletes,useMyComputer(or"Computer")tobrowsetothelocationwhereyouinstalledPythonWin.It'sprobablyinC:
\Python26\ArcGIS10.0\Lib\site-packages\pythonwin.
10.Right-clicktheitemPythonwinandclickCreateShortcut.YoushouldseeaWindowsshortcutappearimmediatelybelowthePythonwinitem.
11.DraganddroptheshortcutontoyourDesktoporwhereverelseyouwanttoputit.
OnWindowsVistaorWindows7,ifyouseeerrormessagesduringinstall,it’slikelythatyoudidnotruntheinstallasanAdministrator.Whenyoulaunchtheinstall,makesureyouright-clickandchooseRunasAdministrator.
Pythonsyntax
Everyprogramminglanguagehasrulesaboutcapitalization,whitespace,howtosetapartlinesofcodeandprocedures,andsoon.HerearesomebasicsyntaxrulestorememberforPython:
∙Pythoniscase-sensitivebothinvariablenamesandreservedwords.Thatmeansit’simportantwhetheryouuseupperorlower-case.Thealllower-case‘print’isareservedwordinPythonthatwillprintavalue,while‘Print’isunrecognizedbyPythonandwillreturnanerror.Likewisearcpyisverysensitiveaboutcaseandwillreturnanerrorifyoutrytorunatoolwithoutcapitalizingthetoolname.
∙YouendaPythonstatementbypressingEnterandliterallybeginninganewline.(Insomeotherlanguages,aspecialcharacter,suchasasemicolon,denotestheendofastatement.)It’sokaytoaddemptylinestodivideyourcodeintologicalsections.
∙Ifyouhavealongstatementthatyouwanttodisplayonmultiplelinesforreadability,youneedtousealinecontinuationcharacter,whichinPythonisabackslash(\).YoucanthencontinuetypingonthelinebelowandPythonwillinterpretthelinesequenceasonestatement.Oneexceptionisifyou’reinthemiddleofparentheses()orbr