speakingphp
phpecho 时间:2021-02-13 阅读:(
)
CopyrightIBMCorporation2010TrademarksPythonbasicsforPHPdevelopersPage1of10PythonbasicsforPHPdevelopersThomasMyerFebruary09,2010AreyouanexperiencedPHPdeveloperwhoneedstolearnPythonThisarticleapproachestheworldofPythondevelopmentfromaPHPdeveloper'sperspective,translatingfamiliarPHPconcepts,suchasvariables,lists,andfunctions,intotheirPythonequivalents.
You'reaPHPdeveloper.
You'veprobablybeenwritingapplicationsforthepastfiveyears(orlonger),andyou'vebuiltjustabouteverythingimaginable—e-commercesystems,simplecontent-managementsystems,TwitterandFacebookintegrations,andahostofcustomutilities.
You'veprobablymaintainedalotofcode,too—everythingfromsimpledisplaypagestocustomapplicationswithtensofthousandsoflinessomebodyelsewrote.
FrequentlyusedacronymsAjax:AsynchronousJavaScript+XMLXML:ExtensibleMarkupLanguageBecauseyou'vespentsomuchtimeworkinginPHP,it'sdoubtfulthatyou'regoingtojumpshiptoanotherlanguage.
Butyoualsoknowthatstandingstillistheonesurerecipefordisasterinthisfield.
Ifnothingelse,learninganewlanguageisliketravelingoverseas:Yougettoseenewthings,tastenewfood,enjoyadifferentculture,havestimulatingconversationswithdifferentpeople,seeneatstuff,thencomebackhometore-evaluateyourusualsurroundings.
ThisarticlegivesyouabitofexposuretoPython.
Itassumesthatyouhavenoknowledgeofthatprogramminglanguage,sosomeofwhatyoureadheremightseemabitbasic.
ItfocusesoncomparingandcontrastingPythonwithPHP—notbecauseonelanguageisbetterthantheotherbutbecauseofasimpletruth:It'softeneasiertolearnnewthingsbyreferringbacktosomethingyoualreadyknow.
Thegoalofthisarticleissimple:togiveyouaquickworkingknowledgeofPythoninthehopethatyou'lldigalittlefurtheronyourown.
Withluck,you'llseethatPythonisn'treallythatdifferentfromwhatyou'reusedto.
Toextendthetravelmetaphor,youaren'treallygoingtoadistantforeignland,justthecountrynextdoorwhereeveryonespeaksthesamelanguageasyou.
WhatisPythonPythonisclassifiedasa"general-purpose,high-levelprogramminglanguage.
"Itisbestknownforbeingincrediblycleanandeasytoread,anditisoneofthefewlanguagesyou'llencounterinwhichwhitespaceandindentationactuallymatter.
Python'sprincipalauthor,GuidoVandeveloperWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage2of10Rossum,isstillveryactiveinthecommunityandhasbeenbestowedthetongue-in-cheektitleof"BenevolentDictatorforLife.
"OneofthenicethingsaboutPythonisitsflexibilityandcompactness.
Itsupportsobject-oriented,structured,aspect-oriented,andfunctionalprogramming,amongotherapproaches.
Pythonwasdesignedwithasmallcoreandalargesetofextensionlibraries,makingthelanguageextremelycompactandflexible.
Fromasyntaxpointofview,you'llfindPythonveryclean—almostmonasticandZen-likeinitssparsity.
PHPdeveloperswilleitherhaveagreatdealofaffectionforthisapproach,findingreliefinthesyntacticaldiscipline,orfinditrestrictive.
Itjustdependsonyouroutlook.
ThePythoncommunityisclearaboutpromotingthisparticularaesthetic,valuingbeautyandsimplicityovercleverhacks.
ThosePHPdevelopers(likemyself)whocameoutofthePerltradition("There'smorethanonewaytodoit")willbeconfrontedwiththetotaloppositephilosophy("Thereshouldonlybeoneobviouswaytodoit").
Infact,thecommunityhasatermforcodethatfollowsapreferredstyle:pythonic.
TosaythatyourcodeispythonicistosaythatisusesPythonidiomswellorthatyou'reshowingnaturalfluencyinthelanguage.
Thisarticledoesn'tbothertryingtobeaPythonista(orPythoneer),butit'ssomethingyouneedtobeawareofifyouwanttocontinuedownthePythonpath.
JustastherearecertainPHP-ishwaystoworkandPerl-ishwaystodothings,takingonPythonmeansthateventually,youneedtostartthinkinginthatlanguage.
Anotherquicknote:PythonwasuptoV3.
0atthetimeofwriting,butthisarticlefocusesonPythonV2.
6.
PythonV3.
0isnotbackward-compatiblewithearlierversions,anditappearsthatV2.
6istheversionmostcommonlyinuse.
Youarefreetousewhateveryouneed,ofcourse.
HowdoesPythondifferfromPHPGenerallyspeaking,PHPisaWebdevelopmentlanguage.
Yes,ithasacommand-lineinterfaceandcanevenbeusedtodevelopembeddedapplications,butforthemostpart,PHPisforWebdevelopment.
Incontrast,PythonisageneralscriptinglanguagethatcanalsobeusedforWebdevelopment.
Inthisway—andIknowI'llbeyelledatforthis—it'sclosertoPerlthanPHP.
(Ofcourse,inallotherways,itcouldn'tbemoredifferent,really.
Butlet'smoveon.
)PHP'ssyntaxislitteredwithdollarsigns($)andcurlybraces({}),whilePythonismorespareandclean.
PHPhasaswitchanddo.
.
.
whileconstruct;Pythondoesn't.
PHPhastheternaryoperator(foobar:baz)andanenormous(andunwieldy)listoffunctionnames,withallkindsofnamingconventions;you'llfindPythonalotcleaner.
PHPhasanarraytypethatdoublesasasasimplelistandadictionaryorhash;Pythonseparatesthetwo.
Pythonalsohasaconceptofmutabilityandimmutability:atuple,forexample,isanimmutablelist.
Youcreateyourtuple,andyoucan'tchangeitafterthat.
Thisconcepttakesabitofgettingusedto,butit'samarvelouswaytoavoiderrors.
Ofcourse,theonlywaytochangeatupleistocopyit,soifyoufindyourselfmakinglotsofchangestoanimmutableobject,youneedtorethinkyourapproach.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage3of10Asnoted,indentationinPythonhasmeaning:You'lllearnthisthehardwayinyourfirstfewdayswiththelanguage.
Youcanalsocreatefunctionsandmethodswithkeyword-basedarguments—anicebreakfromthestandardpositionalargumentsyouseeinPHP.
Theobject-orientedpuristswillenjoyPython'strueobjectorientation,and"first-class"classesandfunctions.
Ifyou'reworkingwithnon-Englishlanguages,you'lllovePython'sstronginternationalizationandUnicodesupport.
You'llalsolovePython'smulti-threadingcapabilities;thiswasoneofthefeaturesthatoriginallyattractedme.
Allthisbeingsaid,PHPandPythonaresimilartoeachotherinmanyways.
Youwon'thaveanytroublecreatingvariables,looping,usingconditionals,andcreatingfunctions.
Youwon'tevenhavethatmuchtroublecreatingreusablemodules.
Theusercommunitiesforbothlanguagesareactiveandpassionate.
PHP'sinstalledbaseisalotbigger,butthishasmoretodowithitspopularityonhostingserversanditsWebfocusthananythingelse.
OK—enoughwiththeintromaterial.
Let'sgetdowntocases.
WorkingwithPythonListing1presentsabasicPythonscripttogetyoustarted.
Listing1.
AsimplePythonscriptforiinrange(20):print(i)Listing2showstheinevitableresult.
Listing2.
ResultsofListing1012345678910111213141516171819Let'slookatafewthingsbeforegoinganyfurther,startingwithvariables.
VariablesAsyoucansee,therearenospecialcharacterstodenoteavariable.
Thevariableiisjustplaini—nothingspecial.
Therearenospecialcharacters(likesemicolonsandbraces)todenoteadeveloperWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage4of10codeblockoranendofstatement,either;justasimplecolon(:)ontheforline.
AlsonotethattheindentationtellsPythonwhatbelongstotheforloop.
Forexample,thecodeinListing3printsanoteaftereachnumberintheloop.
Listing3.
Addingastatementtoeachloopforiinrange(20):print(i)print('alldone')Incontrast,thecodeinListing4putsanoteattheendoftheloop.
Listing4.
Addingastatementafteraloopforiinrange(20):print(i)print('alldone!
')Now,thefirsttimeIlookedatsomethinglikethat,Ithoughtitwassheermadness.
WhatTrustnewlinesandindentstokeepmycodenotonlystructuredbutrunningBelieveme,afterawhile,you'llgetusedtoit(althoughIhavetoadmitthatIkeepreachingforthatsemicolonkeytofinishastatement).
Ifyou'reworkingwithotherdevelopersonaPythonproject,you'llfindthisreadabilityahugebonus.
You'llhavealotfewermomentsof,"Nowwhatdidthiscleverfellowtrytodohere"InPHP,youassignavaluetoavariableusingthe=operator(seeListing5).
InPython,youusethesameoperator,exceptthatyou'resaidtolabelorpointtoavalue.
Tome,it'sjustassigning,soIdon'tworrytoomuchaboutthejargon.
Listing5.
Creatingvariablesyorkie='Marlowe'#meetourYorkieMarlowe!
mutt='Kafka'#meetourmuttKafkaprint(mutt)#printsKafkaPythonvariablenameconventionsaresimilartoPHP:Youcanonlyuseletters,numbers,andtheunderscorecharacter(_)whencreatingavariablename.
Likewise,thefirstcharacterofavariablenamecan'tbeanumber.
Pythonvariablenamesarecase-sensitive,andyoucan'tusecertainPythonkeywords(suchasif,else,while,def,or,and,not,in,andis,forstarters)asvariablenames.
Nobigsurprisesthere.
Pythonallowsyoutodoanynumberofstring-basedoperations.
MostoftheoperationsinListing6willbefamiliartoyou.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage5of10Listing6.
Commonstring-basedoperationsyorkie='Marlowe'mutt='Kafka'ylen=len(yorkie)#lengthofvariableyorkieprint(ylen)#prints7print(len(yorkie))#doesthesamethinglen(yorkie)#alsodoesthesamething,printisimplicitprint(yorkie.
lower())#lowercasesthestringprint(yorkie.
strip('aeiou'))#removesvowelsfromendofstringprint(mutt.
split('f'))#splits"Kafka"into['Ka','ka']print(mutt.
count('a'))#prints2,thenumberofa'sinstringyorkie.
replace('a','4')#replacea'swith4'sConditionalsYoualreadyknowhowtouseaforloop.
Nowlet'stalkaboutconditionals.
You'llfindthatconditionalsareprettymuchthesameasinPHP:You'llhaveaccesstothefamiliarif/else-typestructuresshowninListing7.
Listing7.
Asimpleconditionaltestyorkie='Marlowe'mutt='Kafka'iflen(yorkie)>len(mutt):print('Theyorkiewins!
')else:print('Themuttwins!
')Youcanalsobuildmorecomplexconditionaltestsusinganif/elif/else(elifbeingtheequivalenttoPHP'selseif),asshowninListing8.
Listing8.
Amorecomplexconditionaltestyorkie='Marlowe'mutt='Kafka'iflen(yorkie)+len(mutt)>15:print('Theyorkieandthemuttwin!
')eliflen(yorkie)+len(mutt)>10:print('Tooclosetotell!
')else:print('Nobodywins!
')Asyoucantell,sofarthere'snothingtooexcitinghere.
It'sallprettymuchwhatyouwouldexpect.
NowlookathowPythonhandleslists;you'llseequiteabitofdifferencebetweenthetwolanguages.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage6of10ListsOnecommontypeoflistiscalledatuple,andasnoted,it'simmutable.
Onceyouloadatuplewithaseriesofvalues,youcan'tchangeit.
Tuplescancontainnumbers,strings,variables,andevenothertuples.
Tuplesare0-indexed,asyou'dexpect;youcanaccessthelastitemusingthe-1index.
Therearealsoquiteafewfunctionsyoucanrunontuples.
Listing9.
Tuplesitems=(1,mutt,'Honda',(1,2,3))printitems[1]#printsKafkaprintitems[-1]#prints(1,2,3)items2=items[0:2]#items2nowcontains(1,'Kafka')thankstosliceoperation'Honda'initems#returnsTRUElen(items)#returns4items.
index('Kafka')#returns1,becauseseconditemmatchesthisindexlocationListsareliketuples,exceptthatthey'remutable.
Onceyoucreatethem,youcanadd,subtract,andupdatethevaluesinthelist.
Insteadofparentheses(()),youusesquarebrackets,asshowninListing10.
Listing10.
Listsgroceries=['ham','spam','eggs']len(groceries)#returns3printgroceries[1]#printsspamforxingroceries:printx.
upper()#printsHAMSPAMEGGSgroceries[2]='bacon'groceries#listisnow['ham','spam','bacon']groceries.
append('eggs')groceries#listisnow['ham','spam','bacon','eggs']groceries.
sort()groceries#listisnow['bacon','eggs','ham','spam']Adictionaryislikeanassociativearrayorhash:Ituseskey-valuepairstostoreandretrieveinformation.
Butinsteadofbracketsorparentheses,youusecurlybraces.
Likelists,dictionariesaremutable,whichmeansyoucanadd,subtract,andupdatevaluesinthem.
Listing11.
Dictionariescolorvalues={'red':1,'blue':2,'green':3,'yellow':4,'orange':5}colorvalues#prints{'blue':2,'orange':5,'green':3,'yellow':4,'red':1}colorvalues['blue']#prints2colorvalues.
keys()#retrievesallkeysasalist:#['blue','orange','green','yellow','red']colorvalues.
pop('blue')#prints2andremovesthebluekey/valuepaircolorvalues#afterpop,wehave:#{'orange':5,'green':3,'yellow':4,'red':1}ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage7of10CreatingasimplescriptinPythonNowthatyou'vehadabitofexposuretoPython,let'sbuildasimplePythonscript.
ThisscriptreadsthenumberofPHPsessionfilesinyourserver's/tmpdirectory,thenwritesasummaryreporttoalogfile.
Inthisscript,you'regoingtolearnhowtoimportmodulesforspecificfunctions,howtoworkwithfiles,andhowtowritetoalogfile.
You'llalsosetanumberofvariablestokeeptrackoftheinformationyou'vegathered.
Listing12showstheentirescript.
Openaneditor,andpastethecodeintoitandsavethefileastmp.
pysomewhereonyoursystem.
Thenrunchmod+xonthatfiletomakeitexecutable(assumingyou'reonaUNIXsystem).
Listing12.
tmp.
py#!
/usr/bin/pythonimportosfromtimeimportstrftimestamp=strftime("%Y-%m-%d%H:%M:%S")logfile='/path/to/your/logfile.
log'path='/path/to/tmp/directory/'files=os.
listdir(path)bytes=0numfiles=0forfinfiles:iff.
startswith('sess_'):info=os.
stat(path+f)numfiles+=1bytes+=info[6]ifnumfiles>1:title='files'else:title='file'string=stampstr(numfiles)+"session"\+title+","+str(bytes)+"bytes\n"file=open(logfile,"a")file.
writelines(string)file.
close()Onthefirstline,youseewhat'scalledthehash-bangline,whichidentifiesthelocationofthePythoninterpreter.
Onmysystem,it'sat/usr/bin/python.
Adjustthistotheneedsofyoursystem.
Thenexttwolinesimportspecificmodulesthathelpyoudoyourjob.
Giventhatthescriptneedstodealwithfoldersandfiles,youneedtoimporttheosmodule,asitcontainsvariousfunctionsandmethodsthathelpyoulistfiles,readfiles,andworkwithfolders.
You'llalsobewritingtoalogfile,soit'sagoodideatoaddatimestamptoentries—hence,theneedforthetimefunctions.
Youwon'tneedallofthem,sojustimportthestrftimefunction.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage8of10Inthenextsixlines,yousetvariables.
Thefirst,calledstamp,containsadatestring.
Youusethestrftimefunctiontocreateatimestampwithaspecificformat—inthiscase,astampthatlookslike2010-01-0312:43:03.
Next,createavariablecalledlogfileandputinapathtoafile(itdoesn'tneedtoexistyet)whereyou'llactuallystorelogfilemessages.
Forsimplicity,Iputlogfilesina/logsfolder,butyoucouldputthemanywhere.
Similarly,youneedavariablecalledpaththatcontainsthepathtoyour/tmpdirectory.
Itcanbeanypathyouwantaslongasyouenditwithatrailingslash(/).
Thenextthreevariablesarejustassimple:afileslistthatcontainsallthefilesandfolderslocatedatyourdesignatedpathandtwovariablescalledbytesandnumfiles.
Bothofthosevariablesaresetto0;thescriptincrementsthosevaluesasitprocessesfiles.
Afterallthatcomestheheartofthescript:asimpleforloopthatprocesseseachfileinthefileslist.
Eachtimethroughtheloop,thescriptevaluatesthefilename.
Ifitbeginswithsess_,thenthescriptrunsos.
stat()onthefiletopulloutdataaboutthefile(suchascreationtime,modifytime,andsizeinbytes),incrementsthenumfilescounter,andaddsthenumberofbytesforthisfiletoarunningtotal.
Whentheloopcompletesitsrun,thescriptcheckstoseewhetherthenumfilesvariablecontainsavaluegreaterthan1.
Ifso,itsetsanewvariable,calledtitle,tofiles;otherwise,thetitleissettothesingularformfile.
Thefinalpartofthescriptissimple:Youcreateafinalvariablecalledstring,andinsidethat,youplaceasinglelineofdatathatstartswiththestampandproceedswithnumfiles(convertedtoastring)andthebytes(alsoconvertedtoastring).
Noticethecontinuationcharacter(\);itallowsthecodetoruntothenextline.
It'sagoodtricktoknowforreadability.
Thenyouusetheopen()functiontoopenthelogfileinappendmode(youwanttokeepaddinglinestothefile,afterall),thewritelines()functiontoaddthestringtothelogfile,andtheclose()functiontoclosethefile.
You'venowcreatedasimplePythonscriptyoucandoanythingwith.
Forexample,youcouldsetacronjobtorunthisscriptonceperhourtohelpyoukeeptrackofhowmanyPHPsessionsarebeingusedaroundtheclock.
YoucouldalsousejQueryorsomeotherJavaScriptframeworktohookthisscriptupusingAjaxtogiveyoualog-filefeed(ifso,you'dneedtousetheprintcommandtoreturndata).
ConclusionAsdevelopers,wespendalotoftimeinvestingourselveswithknowledgeaboutspecificlanguagesandapproaches.
Sometimes,doingsoleadstodebatesaboutthesuperiorityofonelanguageoveranother.
I'veparticipatedinmanyofthesedebates,ashavesomeofyou.
Ihavetoadmitthatmostofthesediscussionstendtofallintothesameoldrut—"anythingyoucandoIcandobetter"—whichdoesn'tserveanygoodpurpose.
ibm.
com/developerWorks/developerWorksPythonbasicsforPHPdevelopersPage9of10However,onceyoustartlookingcloselyatanotherlanguage,youfindthatmostlanguageshavesimilartools,philosophies,andapproaches.
Learningyourfirstlanguagecanbedifficult,buttakingwhatyouknowandapplyingittoanotherlanguagecanmakethelearningexperiencealoteasier.
Evenifyoudon'treallytakeupthesecondlanguage,youincreaseyourexposuretoideasandmethodsthatwillimproveyourcraft.
Withanyluck,thisarticlehasprovidedyouwithsomeinsightintoPython.
Myhopeisthatyou'llcontinueyourlearningandkeeplookingintothisgreatlanguage.
YoumayneverleavetheworldofPHP(afterall,it'swhatprobablyputsfoodonthetable),butitneverhurtstokeeplearning.
developerWorksibm.
com/developerWorks/PythonbasicsforPHPdevelopersPage10of10RelatedtopicsVisitPythonandlearnmoreaboutthelanguage.
ReadthePythondocumentation.
TheBeginner'sGuidetoPythonagoodplacetostartlearningaboutthislanguage.
CheckoutthePythonWikiBook,whichisavailableatnocost.
Read"DiscoverPython"togetafullappreciationforPythonandwhatitcando.
PythonCookbook:CheckoutActiveStateCodetofindPythoncodesamplesthatyoucanemploy.
PHP.
netisthecentralresourceforPHPdevelopers.
Checkoutthe"RecommendedPHPreadinglist.
"BrowseallthePHPcontentondeveloperWorks.
FollowdeveloperWorksonTwitter.
ExpandyourPHPskillsbycheckingoutIBMdeveloperWorks'PHPprojectresources.
UsingadatabasewithPHPCheckouttheZendCoreforIBM,aseamless,out-of-the-box,easy-to-installPHPdevelopmentandproductionenvironmentthatsupportsIBMDB2V9.
VisitdeveloperWorksOpenandcollaboratewithsomeofIBM'sbrightestmindsinacommunitysetting.
Startdevelopingwithproducttrials,freedownloads,andIBMBluemixservices.
CopyrightIBMCorporation2010(www.
ibm.
com/legal/copytrade.
shtml)Trademarks(www.
ibm.
com/developerworks/ibm/trademarks/)
iWebFusion(iWFHosting)在部落分享过很多次了,这是成立于2001年的老牌国外主机商H4Y旗下站点,提供的产品包括虚拟主机、VPS和独立服务器租用等等,其中VPS主机基于KVM架构,数据中心可选美国洛杉矶、北卡、本德、蒙蒂塞洛等。商家独立服务器可选5个不同机房,最低每月57美元起,而大流量10Gbps带宽服务器也仅149美元起。首先我们分享几款常规服务器配置信息,以下机器可选择5...
关于HostDare服务商在之前的文章中有介绍过几次,算是比较老牌的服务商,但是商家背景财力不是特别雄厚,算是比较小众的个人服务商。目前主流提供CKVM和QKVM套餐。前者是电信CN2 GIA,不过库存储备也不是很足,这不九月份发布新的补货库存活动,有提供九折优惠CN2 GIA,以及六五折优惠QKVM普通线路方案。这次活动截止到9月30日,不清楚商家这次库存补货多少。比如 QKVM基础的五个方案都...
CloudCone在月初发了个邮件,表示上新了一个系列VPS主机,采用SSD缓存磁盘,支持下单购买额外的CPU、内存和硬盘资源,最低年付17.99美元起。CloudCone成立于2017年,提供VPS和独立服务器租用,深耕洛杉矶MC机房,最初提供按小时计费随时退回,给自己弄回一大堆中国不能访问的IP,现在已经取消了随时删除了,不过他的VPS主机价格不贵,支持购买额外IP,还支持购买高防IP。下面列...
phpecho为你推荐
restrictionsserverbasedcss思科flash支持ipad三星iphonexp如何关闭445端口系统怎么关闭445端口iphone连不上wifi苹果手机为什么突然连不上家里的wifi?iphone连不上wifi苹果手机“无法加入网络”怎么办联通版iphone4s怎么知道到苹果4s是联通版,还是移动版csshack关于CSS hack的写法
花生壳域名 免费网站域名注册 深圳域名注册 中文域名查询 企业域名备案 webhosting 免费个人空间申请 双线主机 中国电信测网速 100m独享 hdd 国外视频网站有哪些 架设邮件服务器 免费ftp 中国联通宽带测试 电信主机托管 ncp是什么 ddos攻击工具 电脑主机配置 大容量存储方案 更多