Introducing Python in ArcGIS.docx

上传人:b****6 文档编号:6029692 上传时间:2023-01-03 格式:DOCX 页数:15 大小:269.24KB
下载 相关 举报
Introducing Python in ArcGIS.docx_第1页
第1页 / 共15页
Introducing Python in ArcGIS.docx_第2页
第2页 / 共15页
Introducing Python in ArcGIS.docx_第3页
第3页 / 共15页
Introducing Python in ArcGIS.docx_第4页
第4页 / 共15页
Introducing Python in ArcGIS.docx_第5页
第5页 / 共15页
点击查看更多>>
下载资源
资源描述

Introducing Python in ArcGIS.docx

《Introducing Python in ArcGIS.docx》由会员分享,可在线阅读,更多相关《Introducing Python in ArcGIS.docx(15页珍藏版)》请在冰豆网上搜索。

Introducing Python in ArcGIS.docx

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

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 自然科学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1