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/)
GreenCloudVPS最近在新加坡DC2节点上了新机器,Dual Xeon Silver 4216 CPU,DDR4内存,10Gbps网络端口,推出了几款大硬盘VPS套餐,基于KVM架构,500GB磁盘起年付30美元。除了大硬盘套餐外,还加推了几款采用NVMe硬盘的常规套餐,最低年付20美元。不过需要提醒的是,机房非直连中国,尤其是电信用户ping值感人,包括新加坡DC1也是如此。大硬盘VPS...
硅云怎么样?硅云是一家专业的云服务商,硅云的主营产品包括域名和服务器,其中香港云服务器、香港云虚拟主机是非常受欢迎的产品。硅云香港可用区接入了中国电信CN2 GIA、中国联通直连、中国移动直连、HGC、NTT、COGENT、PCCW在内的数十家优质的全球顶级运营商,是为数不多的多线香港云服务商之一。目前,硅云香港云服务器,CN2+BGP线路,1核1G香港云主机仅188元/年起,域名无需备案,支持个...
水墨云怎么样?本站黑名单idc,有被删除账号风险,建议转出及数据备份!水墨云ink cloud Service是成立于2017年的商家,自2020起开始从事香港、日本、韩国、美国等地区CN2 GIA线路的虚拟服务器租赁,同时还有台湾、国内nat vps相关业务,也有iplc专线产品,相对来说主打的是大带宽服务器产品。注意:本站黑名单IDC,有被删除账号风险,请尽量避免,如果已经购买建议转出及数据备...
phpecho为你推荐
重庆宽带测速重庆市电信网速测试是哪个网站或ipiexplore.exe应用程序错误iexplore.exe应用程序错误x-routerX-TRAlL是什么意思phpecho在php中 echo和print 有什么区别icloudiphone没开启icloud的iphone怎么用find my iphone找回csshack针对IE6的CSS HACK是什么?googleadsencegoogle adsense打不开怎么办fastreport2.5现在化工中,法兰中pn2.5是什么意思ios6.1.3完美越狱6.1.3怎么完美越狱搜狗浏览器2.2搜狗浏览器怎么恢复以前的版本?
备案域名 mediafire下载工具 10t等于多少g 免费个人博客 新站长网 777te 165邮箱 傲盾官网 免费dns解析 国外ip加速器 多线空间 个人免费主页 移动服务器托管 独享主机 1美元 博客域名 mteam 腾讯云平台 .htaccess 第八届中美互联网论坛 更多