cltk编程及应用简介.ppt
Allrightsreserved2010,AlcatelShanghaiBellProductTest-Shanghai/April2010Tcl and the Tk ToolkitChenTaoApril,2010Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010OutlinesTcl/TkAroundUsTcl/TkOverviewBasicTclSyntaxIntroductionforTkIntroductionforExpectHomebrewTestAutomationFrameworkTheSURofTAOProjectResourcesAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Tcl/TkAroundUsAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010FromWorkPlaceInWCSInITE/8610nUsingExpecttocommunicatewithWCS:send CLI commands and get response.InCiscoIOSRouterenableRouter#tclshRouter(tcl)#puts$tcl_version8.3TestAutomationforTelecommunicationandNetworkEquipmentsAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ToOurDailyLifeItseasytodesignhandyprogramsbasedonTcltofulfilldifferenttasksnAfishscreensaveprogramnAe-pianonAPaintingpadAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Tcl/TkOverview-Say“tickle tee-kay”Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTclTclstandsforToolCommandLanguagenJohOusterhout,UniversityofCalifornia.nFirstreleasewasin1989.Asimplescriptinglanguage:nCrossplatformsupport.Tclcanrunonmostpopularoperationsystemsuchasunix/linux,Windows,MacintoshandsoforthnScriptsareinterpretedatruntime.Whichmakesthedevelopmentcyclefasterthancompiledlanguages,nowaitingforlongcompilationsnThecapabilitytocallC/C+routinesnSimilartoothershelllanguagessuchasUNIXCshell,Perl,VB.“EasyEasy”tostudynExcellenttextanalysiscompetenceAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTcl(cont)Un-typedandastring-basedcommandlanguagenDatatypesarenotusedwhenvariablesaredefined.Youneedntspecifyavariableasinteger,floatorastring.nThebasicmechanismsareallrelatedtostringsandstringsubstitutionsAllvariablesarestoredasstrings.automatictypeconversionincontextsetx10;#createavariable“x”andgiveavalue“10”toitsety20;#createavariable“y”andgiveavalue“20”toitsetzexpr$x+$y;#xplusyandsaveresultin“z”sety“Imastringnow.IndeedImalwaysstring:-)”puts“Expressionresultis:$z”;#printresultonstandardoutputs“Ybecomesas:”$y”setaArray“JackboyMerrygirl”;#defineanarrayputs“Imanarray,butastringindeed:n$aArray”Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTcl(cont)EasytoextendnTherearenumerousfreeextensionsbuiltontopofTcl/TkforspecificfunctionsavailableontheInternet.Tclx:HandlingsignaleventsNet-Snmp:supportsnmpcommuninicationBWidget/IWidgetetc.:TkextensionsprovidesspecialandpowerfulwidgetsHttp&ncgi:forhttpserverprogrammingnItiseasytoaddnewTclprimitivesbywritingCproceduresTcl/TkisPureCOpen-Sourcecode,newTclcommandscanbeimplementedbyspecificextensionsprogrammedinC,fairlyeasywithoutchangingTclcore.TotallyFree!Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTkTknATcl-basedtoolkitforprogramminggraphicaluserinterfacesnQuickandeasytobuildpowerfuluserinterfaces.nPortable,onecopyofscriptcanworkunchangedonUNIX,Windows,andtheMacintosh.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsExpectExpectnATcl-basedToolkitforAutomatingInteractiveProgramsTheprograminteractivelypromptandexpectusertoenterkeystrokesinresponsenAdefaultcommandinsomeoperationsystemsnTheresalsoanExpectextensionfortclwhichcanalsobeloadedtotclshellAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010TclnotsogoodnewsInterpretedlanguagesrunslowerandusemoreprocessingtimeoroverheadWithoutacomplier,syntaxerrorscantbefounduntilthescriptisexecutedUn-typedlanguagesdonotallowforthemostefficienttranslationofcodeAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010BasicTclSyntaxAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010TclCommandsFormatATclscriptconsistsofoneormorecommandsnCommandsareseparatedbynewlinesorsemi-colonsAscriptwithtwocommandsseparatedbyanewlinecharacter:seta24setb25Abovescriptcouldbewrittenonasinglelineusingasemi-colonseparator:seta24;setb25BasicallyeachcommandconsistsofoneormorewordsnFirstwordisthenameofacommandnAdditionalwordsareargumentstothatcommandnWordsareseparatedbyspacesandtabsvar1var2Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010VariableNeedntdeclarethetypeofvariable,automaticconversionincontextset x“10.99”;#this is a stringputs“expr int($x)”;#output would be 10NeedtobedeclaredandassignedavaluebeforeuseVariablenameiscase-sensitiveAssignmentexpression:setTousevalueofavariable,puta“$”aheadofitas$nIfyouwanttoappendextracharacterstoavariable,usebracesaroundvariablenameas:set x“Hello ”puts“$xJack!”;#This is wrong,it would treat xJack as variable nameputs“$xJack!”;#This is right!Differentscopesshouldsharevariablevaluesbyspecificmethods.nnamespacenprocedureTouseglobaltovisitglobalvariablesnchildreninterpreterAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010CommentsCommentissetinashellway,leadingbya“#”seta(“john”)boy;#Setvalueofelement“john”ofarray“a”as“boy”#Orwecandoasarrayseta“johnboy”;#Ifyoulik,youcancommentusingmulti-linesBecarefulwhenaddcommentstoa“switch”expressionswitchvar“go”tohandlego#Ifitdoesnotsupportfollowingvalue,commentitlater:=Wrong!“pause.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010StandardOutput&InputI/Ooperationforstandardinputandoutput,normallytheterminalinfrontofus.Printoutonterminal:puts“abcdefgNoThanks.”Formatthestringbyusing“format”commandnSimilarasCset str format“%-2d%20s%9d”,193 is not equal to 0133;#octal number“193 is not equal to 91”Getinput:puts-nonewline“Your name please:”gets stdin sNameAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010MathandLogicalExpressionexprexprexpr1+2;setx10;sety20;expr$x+$y=30exprabs(-10)=10expr10*rand()=9.06197207004855;#resultisdouble,0value5;#inrangeof07incrsetx1incrx=2incrx3=5incrx-2=3logic“and”“or”.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Control:BranchandLoopIf.elseif.else.ifBoolean expressionifxxxelseifxxxelseif elseForsetsum0;forseti0;sety10$i450Whilewhilegets$fdline=0Switchswitch-exact$xyz“0”;?break?;“1”?default?Foreach(refertooperationoflist)Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010List,Array&Operation“list”representalistofstringnCommandsforlistlist,lindex,lrange,lappend,lreplacesplit,joinArrayissimilarasthe“associate”arrayorhashdatainperlorphp.%set lst1“Jack boy blue Merry girl red”;#or%set lst2 list Red White Yellow Blue%foreach x$lstputs“$xn”%foreachx y z$lst1 puts student name:$x,a$y,who likes$zstudent name:Jack,a boy,who likes bluestudent name:Merry,a girl,who likes redputs lindex$lst2 2=Whiteputs lindex$lst2 0=Red%array setaArrlistJackboyMerrygirl%parrayaArraArr(Jack)=boyaArr(Merry)=girl%array getaArrJack boy Merry girl%array namesaArrJack Merry%array sizeaArr2%foreach x y array get aArr puts Name:$x,a$yName:Jack,a boyName:Merry,a girlAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010String&Operationappendformatsubststringcommandnstringcomparenstringmatchnstringequal(addedin8.4)nstringrangenstringtolower/touppernstringtrimstringcomparation:nif$str1=$str2putsequalnstringcomparingcommandssuchas“stringmatch”stringclasscheck:nstringisifstringisinteger10putsokAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ProcandReturnProcedureintclsimilarasfunctioninC,perl,php,unixshelletc.nprocarg1arg2.argsprocbodynreturnstringproccalc1opa“opb10”returnexpr$opa+$opbcalc123=5calc12=12proccalc2args;#Varyargumentlistsetopalindex$args0setopblindex$args1returnexpr$opa+$opbglobalvariablenInaprocedure,use“global”tomakeaglobalvariablevisiblefrominsideofprocedureAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010FileI/OWritefile%setfdopenabcw+=filef76ec0%puts$fdabcdn%puts$fdefgtn%flush$fd%close$fdReadfile%setfdopenabcr=filef840d8nGetfilecontentlinebyline%whilegets$fdline!=-1puts-nonewline$line=abcd efgtnRead commandread?chunk bytes?set str read$fdwhile!eof$fd svet buf read$fd 10000 .Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Socket&FileEventsocket?-myaddr addr?-myport myport?-async?host portsocket-server command?-myaddr addr?portNOTE:“port”specifiedhereisthe“listening”portwhichcantbeusedtotransferdata.Astheconnectionrequestisaccepted,anewsocketwillbecreatedfortransportdata.proc Accept newSock addr port global sock_arrputs Accepted$newSock from$addr port$portset sock_arr(addr,$newSock)list$addr$portfconfigure$newSock-blocking 0 buffering nonefileevent$newSock readable list Echo$newSockset status catch socket-server Accept$SERVER_PORT ssif!$status set sock_arr(main)$ss puts Create server socket success.Servers socket is$ss else error Create servers socket failed:$ssprocEchosockglobalsock_arrifeof$sock|catchgets$socklinereturnputs$sockstringtoupper$lineflush$sockAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010VariableinterpolationHappensindoublequote“”andnormalexpressionssetx“Hello”puts“$xJack!”setylist$xJack“!”Interpolationwouldbeprohibitedinmostkindsofbraces puts$x Jack theresultwouldbe:$xJackItsnotalwayssuchthingforbrace,braceinsomecommandwillnotprohibitvariablereplacement:catcherrforifAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ErrorHandling&DiagnosticMulti-linecommandsetxlistNanjingBeijinglistShenYangDaliannShouldnospecialcharacterexceptforcarriage-return/newlinenShouldnotputcommentafterthe“catch”commandcatchcommandncatcherrors,butwouldnotbreaktheprocessnerrorinformationtobesavedasthe“errorInfo”globalvariablenStoreerrorinformationthe“error”commandnerrorcommandcancauseanerror,error“line50brokenformismatchedvalue”=Thiserrorcanbecapturedby“catch”commandandreturn1,anderrorstringwillbesettoerrorInfo.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010RegularExpressionSyntax-Commandsregexpregexp?flags?patternstring?matchsub1sub2.?#GetIPaddressout,andlastnumberregexp0-91,3.0-91,3.:digit:+.(:digit:1,3)IPAddress:172.24.229.3sMatchsVar1regsubregsub?switches?patternstringsubspecvarnameAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010RegularExpressionSyntax-BasicMatchingcharactersnMostcharacterssimplymatchthemselvesntheperiod,“.”,matchesanysinglecharacterabmatchesab;“a.”matchanafollowedbyanycharactor.Charactersetsna-zmatchesanycharacterinthisrangena-zmatchesanycharacterisntinthisrange,=notnmatchesorQuantifiersn*forzeroormore:a*matcheszeroormoreas.“.*”matchesanythingn+foronceormore:a+matchesa,aa,aa.an?zeroorone:a?matcheszerooroneaAlternation(orbranch)n(H|h)ellomatchesHelloandhello,sameashello|HelloAnchorn:matchesthebeginningofastringn$:matchestotheendofastring:.*$matchesawholelinewithanything,evenemptylineBachslashQuotingnToturnoffspecialmeansoffollowingcharacter:.*?+()$|Capturingsub-patternsngroupedwithparentheses“Im.*IPaddress(0-9+.0-9+.0-9+.0-9+)$”NOTE:sub-patternswillbecapturedandsaveinspecificvariables.Ifuse(?:pattern),patternwillbecapturedbutnotsaved,commandwillbefasterAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010RegularExpressionSyntax-Advancedcharacterclassesn:digit:=0-9=dn:alpha:=A-Za-zn:space:=bfnrtv=sNongreedyQuantifiersnBydefaultquantifier+*?willmatchasmanycharactersaspossible.Use“?”behindthemcanprohibitsuch.+nmatchesasmanylinesaspossibletilllastline.+?nmatchesjustonelineBoundQuantifiersm,nmatcheslatestmtimes,andmaximumntimesBackreferencesNOTE:regsubdoesnotsupportthefunctionofusingback-referencesoutsideofregularexpressioninperls/(S+)s+(S+)/$2$1/Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010SignalSIGHUPHangupSIGINTInterruptSIGQUITquitSIGKILLkillSIGPIPESIGTERMSIGSTOPSIGTSTPSIGCONTSIGHLDSIGWINCHwindowsizechangeSIGUSR1SIGUSR2trap call back scripts sig_nametrapputs“byebye”;exitSIGINTAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010TimeEvent:theaftercommandproc Circle global switcherif$switcher=off#kill all after event,and then return#do something for repeatafter 1000 Circlenafter millisecondsnafter ms arg?arg.?nafter cancel idnafter cancel commandnafter idle commandnafter info?id?Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010IntroductionforTkAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010CreatechildrenwidgetsWindowisorganizedinahierarchynAprimarywindow-therootofthehierarchy,isthemainwindowoftheapplicationnamedas“.”.nWidgetsinprimarywindowareitschildrenwindow,namedas“.”nAndchildwindowcanhasitsownchildren.“.”nFirstcharactorofshouldbeinlower-caseoradigitalnumberframe.fButframe.fText.fBut configure-borderwidth 1;.fText configure-borderwidth 1 entry .fBut.eEnt -width 20set bBut button.fBut.bHello-text HELLO!.fBut.eEnt configure-bg pink.fBut.bHello configure-command.fBut.eEnt insert end hello!;.fText.tText insert end Hello set tTr text.fText.tText-yscrollcommand.fText.yscroll set -xscrollcommand.fText.xscroll set$tTr configure-width 40-height 20-foreground brown-wrap wordscrollbar.fText.yscroll-command$tTr yview-orient verticalscrollbar.fText.xscroll-command$tTr xview-orient horizontalAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010DisplayWidgets Put and display widgets in main window:n.fBut:a Framework contains a single line text input entryn.fText:a Framework contains a text will scrollbarn.fBut.eEnt:The entrynset bBut.fBut.bHello:A buttonnset tTr .fText.text:Text bodyn.fText.yscroll :X scroll bar(horizontal)n.fText.xscroll :Y scroll bar(vertical)Three main geometry managernpack:constraint-based geometry managerngrid:control in detailnplace:place a widget in another onepack.fBut.fText-side left-fill both-expand truegrid.fBut.eEnt-sticky newsgrid$bBut-sticky newsgrid$tTr.fText.yscroll-sticky newsgrid.fText.xscroll-sticky ewgrid rowconfigure.fText 0-weight 1grid columnconfigure.fText 0-weight 1grid propagate.fText falseAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ASimpleMenumenubutton.mb-textFile-menu.mb.menupack.mb-padx10-pady10setmmenu.mb.menu-tearoff1$maddcommand-labelHello-commandputsHello,World!$maddcheck-labelBoolean-variablefoo-commandputsfoo=$foo$maddseparator$maddcascade-labelFruit-menu$m.sub1setm2menu$m.sub1-tearoff0$m2addradio-labelapple-variablefruit-valueapple$m2addradio-labelorange-variablefruit-valueorange$m2addradio-labelkiwi-variablefruit-valuekiwinote:to add menu in BsPmMonitorGuiAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010IntroductionforExpectAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ExpectCommandsSyntaxspawnnspawntelnetnreturnapidnsavehandleinlocalvariable“spawn_id”sendnaliasofexp_sendnWhenusetogetherwithTk,exp_sendisprefer.expectexpect-re“Password:”-re“UserName:”.exp_continueeoftimeoutinteractcloseexp_internal0|1log_fileoptionsof“send”n-hsetsend_human.1.31.052setsend_human.4.4.2.5100nsend-ssetsend_slow10,.001timeoutAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010user_spawn_iduser_spawn_idfifoinoutspawn_iduser_spawn_iduser_spawn_idfifoinoutspawn_id No.1spawn_id No.2inoutExpectExpectfifoinoutfifostandard I/OAllrightsreserved2010,AlcatelShanghaiBel