《cltk编程及应用简介.ppt》由会员分享,可在线阅读,更多相关《cltk编程及应用简介.ppt(53页珍藏版)》请在taowenge.com淘文阁网|工程机械CAD图纸|机械工程制图|CAD装配图下载|SolidWorks_CaTia_CAD_UG_PROE_设计图分享下载上搜索。
1、Allrightsreserved2010,AlcatelShanghaiBellProductTest-Shanghai/April2010Tcl and the Tk ToolkitChenTaoApril,2010Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010OutlinesTcl/TkAroundUsTcl/TkOverviewBasicTclSyntaxIntroductionforTkIntroductionforExpectHomebrewTestAutomationFrameworkT
2、heSURofTAOProjectResourcesAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Tcl/TkAroundUsAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010FromWorkPlaceInWCSInITE/8610nUsingExpecttocommunicatewithWCS:send CLI commands and get response.InCiscoIOSRouterenableRo
3、uter#tclshRouter(tcl)#puts$tcl_version8.3TestAutomationforTelecommunicationandNetworkEquipmentsAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ToOurDailyLifeItseasytodesignhandyprogramsbasedonTcltofulfilldifferenttasksnAfishscreensaveprogramnAe-pianonAPaintingpadAllrightsreserv
4、ed2010,AlcatelShanghaiBellProductTestShanghai/April2010Tcl/TkOverview-Say“tickle tee-kay”Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTclTclstandsforToolCommandLanguagenJohOusterhout,UniversityofCalifornia.nFirstreleasewasin1989.Asimplescriptinglanguage:nCrossplatformsu
5、pport.Tclcanrunonmostpopularoperationsystemsuchasunix/linux,Windows,MacintoshandsoforthnScriptsareinterpretedatruntime.Whichmakesthedevelopmentcyclefasterthancompiledlanguages,nowaitingforlongcompilationsnThecapabilitytocallC/C+routinesnSimilartoothershelllanguagessuchasUNIXCshell,Perl,VB.“EasyEasy”
6、tostudynExcellenttextanalysiscompetenceAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTcl(cont)Un-typedandastring-basedcommandlanguagenDatatypesarenotusedwhenvariablesaredefined.Youneedntspecifyavariableasinteger,floatorastring.nThebasicmechanismsareallrelatedtostringsand
7、stringsubstitutionsAllvariablesarestoredasstrings.automatictypeconversionincontextsetx10;#createavariable“x”andgiveavalue“10”toitsety20;#createavariable“y”andgiveavalue“20”toitsetzexpr$x+$y;#xplusyandsaveresultin“z”sety“Imastringnow.IndeedImalwaysstring:-)”puts“Expressionresultis:$z”;#printresultons
8、tandardoutputs“Ybecomesas:”$y”setaArray“JackboyMerrygirl”;#defineanarrayputs“Imanarray,butastringindeed:n$aArray”Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTcl(cont)EasytoextendnTherearenumerousfreeextensionsbuiltontopofTcl/TkforspecificfunctionsavailableontheInternet
9、.Tclx:HandlingsignaleventsNet-Snmp:supportsnmpcommuninicationBWidget/IWidgetetc.:TkextensionsprovidesspecialandpowerfulwidgetsHttp&ncgi:forhttpserverprogrammingnItiseasytoaddnewTclprimitivesbywritingCproceduresTcl/TkisPureCOpen-Sourcecode,newTclcommandscanbeimplementedbyspecificextensionsprogrammedi
10、nC,fairlyeasywithoutchangingTclcore.TotallyFree!Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsTkTknATcl-basedtoolkitforprogramminggraphicaluserinterfacesnQuickandeasytobuildpowerfuluserinterfaces.nPortable,onecopyofscriptcanworkunchangedonUNIX,Windows,andtheMacintosh.All
11、rightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010WhatsExpectExpectnATcl-basedToolkitforAutomatingInteractiveProgramsTheprograminteractivelypromptandexpectusertoenterkeystrokesinresponsenAdefaultcommandinsomeoperationsystemsnTheresalsoanExpectextensionfortclwhichcanalsobeloadedtotcl
12、shellAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010TclnotsogoodnewsInterpretedlanguagesrunslowerandusemoreprocessingtimeoroverheadWithoutacomplier,syntaxerrorscantbefounduntilthescriptisexecutedUn-typedlanguagesdonotallowforthemostefficienttranslationofcodeAllrightsreserved20
13、10,AlcatelShanghaiBellProductTestShanghai/April2010BasicTclSyntaxAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010TclCommandsFormatATclscriptconsistsofoneormorecommandsnCommandsareseparatedbynewlinesorsemi-colonsAscriptwithtwocommandsseparatedbyanewlinecharacter:seta24setb25Abov
14、escriptcouldbewrittenonasinglelineusingasemi-colonseparator:seta24;setb25BasicallyeachcommandconsistsofoneormorewordsnFirstwordisthenameofacommandnAdditionalwordsareargumentstothatcommandnWordsareseparatedbyspacesandtabsvar1var2Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Va
15、riableNeedntdeclarethetypeofvariable,automaticconversionincontextset x“10.99”;#this is a stringputs“expr int($x)”;#output would be 10NeedtobedeclaredandassignedavaluebeforeuseVariablenameiscase-sensitiveAssignmentexpression:setTousevalueofavariable,puta“$”aheadofitas$nIfyouwanttoappendextracharacter
16、stoavariable,usebracesaroundvariablenameas:set x“Hello ”puts“$xJack!”;#This is wrong,it would treat xJack as variable nameputs“$xJack!”;#This is right!Differentscopesshouldsharevariablevaluesbyspecificmethods.nnamespacenprocedureTouseglobaltovisitglobalvariablesnchildreninterpreterAllrightsreserved2
17、010,AlcatelShanghaiBellProductTestShanghai/April2010CommentsCommentissetinashellway,leadingbya“#”seta(“john”)boy;#Setvalueofelement“john”ofarray“a”as“boy”#Orwecandoasarrayseta“johnboy”;#Ifyoulik,youcancommentusingmulti-linesBecarefulwhenaddcommentstoa“switch”expressionswitchvar“go”tohandlego#Ifitdoe
18、snotsupportfollowingvalue,commentitlater:=Wrong!“pause.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010StandardOutput&InputI/Ooperationforstandardinputandoutput,normallytheterminalinfrontofus.Printoutonterminal:puts“abcdefgNoThanks.”Formatthestringbyusing“format”commandnSimilar
19、asCset 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)=
20、10expr10*rand()=9.06197207004855;#resultisdouble,0value5;#inrangeof07incrsetx1incrx=2incrx3=5incrx-2=3logic“and”“or”.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010Control:BranchandLoopIf.elseif.else.ifBoolean expressionifxxxelseifxxxelseif elseForsetsum0;forseti0;sety10$i450W
21、hilewhilegets$fdline=0Switchswitch-exact$xyz“0”;?break?;“1”?default?Foreach(refertooperationoflist)Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010List,Array&Operation“list”representalistofstringnCommandsforlistlist,lindex,lrange,lappend,lreplacesplit,joinArrayissimilarasthe“as
22、sociate”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 li
23、ndex$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,AlcatelShanghaiBellProductTestShangha
24、i/April2010String&Operationappendformatsubststringcommandnstringcomparenstringmatchnstringequal(addedin8.4)nstringrangenstringtolower/touppernstringtrimstringcomparation:nif$str1=$str2putsequalnstringcomparingcommandssuchas“stringmatch”stringclasscheck:nstringisifstringisinteger10putsokAllrightsrese
25、rved2010,AlcatelShanghaiBellProductTestShanghai/April2010ProcandReturnProcedureintclsimilarasfunctioninC,perl,php,unixshelletc.nprocarg1arg2.argsprocbodynreturnstringproccalc1opa“opb10”returnexpr$opa+$opbcalc123=5calc12=12proccalc2args;#Varyargumentlistsetopalindex$args0setopblindex$args1returnexpr$
26、opa+$opbglobalvariablenInaprocedure,use“global”tomakeaglobalvariablevisiblefrominsideofprocedureAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010FileI/OWritefile%setfdopenabcw+=filef76ec0%puts$fdabcdn%puts$fdefgtn%flush$fd%close$fdReadfile%setfdopenabcr=filef840d8nGetfilecontent
27、linebyline%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
28、?-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$portfconfigu
29、re$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|
30、catchgets$socklinereturnputs$sockstringtoupper$lineflush$sockAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010VariableinterpolationHappensindoublequote“”andnormalexpressionssetx“Hello”puts“$xJack!”setylist$xJack“!”Interpolationwouldbeprohibitedinmostkindsofbraces puts$x Jack the
31、resultwouldbe:$xJackItsnotalwayssuchthingforbrace,braceinsomecommandwillnotprohibitvariablereplacement:catcherrforifAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010ErrorHandling&DiagnosticMulti-linecommandsetxlistNanjingBeijinglistShenYangDaliannShouldnospecialcharacterexceptfo
32、rcarriage-return/newlinenShouldnotputcommentafterthe“catch”commandcatchcommandncatcherrors,butwouldnotbreaktheprocessnerrorinformationtobesavedasthe“errorInfo”globalvariablenStoreerrorinformationthe“error”commandnerrorcommandcancauseanerror,error“line50brokenformismatchedvalue”=Thiserrorcanbecapture
33、dby“catch”commandandreturn1,anderrorstringwillbesettoerrorInfo.Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010RegularExpressionSyntax-Commandsregexpregexp?flags?patternstring?matchsub1sub2.?#GetIPaddressout,andlastnumberregexp0-91,3.0-91,3.:digit:+.(:digit:1,3)IPAddress:172.24
34、.229.3sMatchsVar1regsubregsub?switches?patternstringsubspecvarnameAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010RegularExpressionSyntax-BasicMatchingcharactersnMostcharacterssimplymatchthemselvesntheperiod,“.”,matchesanysinglecharacterabmatchesab;“a.”matchanafollowedbyanychar
35、actor.Charactersetsna-zmatchesanycharacterinthisrangena-zmatchesanycharacterisntinthisrange,=notnmatchesorQuantifiersn*forzeroormore:a*matcheszeroormoreas.“.*”matchesanythingn+foronceormore:a+matchesa,aa,aa.an?zeroorone:a?matcheszerooroneaAlternation(orbranch)n(H|h)ellomatchesHelloandhello,sameashel
36、lo|HelloAnchorn:matchesthebeginningofastringn$:matchestotheendofastring:.*$matchesawholelinewithanything,evenemptylineBachslashQuotingnToturnoffspecialmeansoffollowingcharacter:.*?+()$|Capturingsub-patternsngroupedwithparentheses“Im.*IPaddress(0-9+.0-9+.0-9+.0-9+)$”NOTE:sub-patternswillbecapturedand
37、saveinspecificvariables.Ifuse(?:pattern),patternwillbecapturedbutnotsaved,commandwillbefasterAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010RegularExpressionSyntax-Advancedcharacterclassesn:digit:=0-9=dn:alpha:=A-Za-zn:space:=bfnrtv=sNongreedyQuantifiersnBydefaultquantifier+*?
38、willmatchasmanycharactersaspossible.Use“?”behindthemcanprohibitsuch.+nmatchesasmanylinesaspossibletilllastline.+?nmatchesjustonelineBoundQuantifiersm,nmatcheslatestmtimes,andmaximumntimesBackreferencesNOTE:regsubdoesnotsupportthefunctionofusingback-referencesoutsideofregularexpressioninperls/(S+)s+(
39、S+)/$2$1/Allrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010SignalSIGHUPHangupSIGINTInterruptSIGQUITquitSIGKILLkillSIGPIPESIGTERMSIGSTOPSIGTSTPSIGCONTSIGHLDSIGWINCHwindowsizechangeSIGUSR1SIGUSR2trap call back scripts sig_nametrapputs“byebye”;exitSIGINTAllrightsreserved2010,Alcatel
40、ShanghaiBellProductTestShanghai/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?Allri
41、ghtsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010IntroductionforTkAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010CreatechildrenwidgetsWindowisorganizedinahierarchynAprimarywindow-therootofthehierarchy,isthemainwindowoftheapplicationnamedas“.”.nWidgetsinprimaryw
42、indowareitschildrenwindow,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 p
43、ink.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 vertical
44、scrollbar.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.eE
45、nt: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 le
46、ft-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/April2010
47、ASimpleMenumenubutton.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-variablef
48、ruit-valueapple$m2addradio-labelorange-variablefruit-valueorange$m2addradio-labelkiwi-variablefruit-valuekiwinote:to add menu in BsPmMonitorGuiAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April2010IntroductionforExpectAllrightsreserved2010,AlcatelShanghaiBellProductTestShanghai/April
49、2010ExpectCommandsSyntaxspawnnspawntelnetnreturnapidnsavehandleinlocalvariable“spawn_id”sendnaliasofexp_sendnWhenusetogetherwithTk,exp_sendisprefer.expectexpect-re“Password:”-re“UserName:”.exp_continueeoftimeoutinteractcloseexp_internal0|1log_fileoptionsof“send”n-hsetsend_human.1.31.052setsend_human
50、.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