Introducing Python in ArcGIS.docx
- 文档编号:6029692
- 上传时间:2023-01-03
- 格式:DOCX
- 页数:15
- 大小:269.24KB
Introducing Python in ArcGIS.docx
《Introducing Python in ArcGIS.docx》由会员分享,可在线阅读,更多相关《Introducing Python in ArcGIS.docx(15页珍藏版)》请在冰豆网上搜索。
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
- 配套讲稿:
如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。
- 特殊限制:
部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。
- 关 键 词:
- Introducing Python in ArcGIS