tcltk编程及应用简介课件_第1页
tcltk编程及应用简介课件_第2页
tcltk编程及应用简介课件_第3页
tcltk编程及应用简介课件_第4页
tcltk编程及应用简介课件_第5页
已阅读5页,还剩47页未读 继续免费阅读

下载本文档

版权说明:本文档由用户提供并上传,收益归属内容提供方,若内容存在侵权,请进行举报或认领

文档简介

1、OutlinesTcl/Tk Around UsTcl/Tk OverviewBasic Tcl SyntaxIntroduction for TkIntroduction for ExpectHomebrew Test Automation FrameworkThe SUR of TAO ProjectResourcesOutlinesTcl/Tk Around UsTcl/TkAround UsTcl/TkFrom WorkPlaceIn WCSIn ITE/8610Using Expect to communicate with WCS : send CLI commands and g

2、et response.In Cisco IOSRouterenableRouter#tclshRouter(tcl)#puts $tcl_version8.3Test Automation for Telecommunication and Network Equipments From WorkPlaceIn WCSTo Our Daily LifeIts easy to design handy programs based on Tcl to fulfill different tasksA fish screen save programA e-pianoA Painting pad

3、To Our Daily LifeIts easy to Tcl/TkOverview-Say “tickle tee-kay”Tcl/Tk-Say “tickle tee-kay”Whats TclTcl stands for Tool Command LanguageJoh Ousterhout, University of California.First release was in 1989.A simple scripting language:Cross platform support. Tcl can run on most popular operation system

4、such as unix/linux, Windows, Macintosh and so forth Scripts are interpreted at run time. Which makes the development cycle faster than compiled languages, no waiting for long compilations The capability to call C/C+ routinesSimilar to other shell languages such as UNIX C shell, Perl, VB. “Easy” to s

5、tudyExcellent text analysis competenceWhats TclTcl stands for Tool Whats Tcl (cont)Un-typed and a string-based command languageData types are not used when variables are defined. You neednt specify a variable as integer, float or a string.The basic mechanisms are all related to strings and string su

6、bstitutions All variables are stored as strings. automatic type conversion in contextset x 10 ;#create a variable “x” and give a value “10” to itset y 20; #create a variable “y” and give a value “20” to itset z expr $x + $y ;# x plus y and save result in “z”set y “Im a string now. Indeed Im always s

7、tring:-)”puts “Expression result is: $z”; #print result on standard outputs “Y becomes as: ”$y”set aArray “Jack boy Merry girl” ;# define an arrayputs “Im an array, but a string indeed:n $aArray”Whats Tcl (cont)Un-typed andWhats Tcl (cont)Easy to extend There are numerous free extensions built on to

8、p of Tcl/Tk for specific functions available on the Internet.Tclx: Handling signal eventsNet-Snmp : support snmp communinicationBWidget/IWidget etc.: Tk extensions provides special and powerful widgetsHttp & ncgi: for http server programmingIt is easy to add new Tcl primitives by writing C procedure

9、s Tcl/Tk is Pure C Open-Source code, new Tcl commands can be implemented by specific extensions programmed in C , fairly easy without changing Tcl core.Totally Free! Whats Tcl (cont)Easy to exteWhats TkTkA Tcl-based toolkit for programming graphical user interfacesQuick and easy to build powerful us

10、er interfaces. Portable , one copy of script can work unchanged on UNIX, Windows, and the Macintosh. Whats TkTkWhats ExpectExpectA Tcl-based Toolkit for Automating Interactive ProgramsThe program interactively prompt and expect user to enter keystrokes in responseA default command in some operation

11、systemsTheres also an Expect extension for tcl which can also be loaded to tcl shellWhats ExpectExpectTcl not so good newsInterpreted languages run slower and use more processing time or overheadWithout a complier,syntax errors cant be found until the script is executedUn-typed languages do not allo

12、w for the most efficient translation of codeTcl not so good newsInterpreteBasic Tcl SyntaxBasic Tcl SyntaxTcl Commands FormatA Tcl script consists of one or more commandsCommands are separated by newlines or semi-colonsA script with two commands separated by a newline character:set a 24set b 25Above

13、 script could be written on a single line using a semi-colon separator:set a 24; set b 25 Basically each command consists of one or more wordsFirst word is the name of a commandAdditional words are arguments to that commandWords are separated by spaces and tabs var1 var2 Tcl Commands FormatA Tcl scr

14、iVariableNeednt declare the type of variable, automatic conversion in contextset x “10.99”; # this is a stringputs “expr int($x)”;# output would be 10Need to be declared and assigned a value before useVariable name is case-sensitiveAssignment expression : set To use value of a variable, put a “$” ah

15、ead of it as $If you want to append extra characters to a variable, use braces around variable name as: set x “Hello ”puts “$xJack!”; # This is wrong, it would treat xJack as variable nameputs “$xJack!”;#This is right!Different scopes should share variable values by specific spaceprocedu

16、reTo use global to visit global variableschildren interpreterVariableNeednt declare the tyCommentsComment is set in a shell way, leading by a “#” set a(“john”) boy ;#Set value of element “john” of array “a” as “boy”# Or we can do asarray set a “john boy”;#If you lik, you cancomment using multi-lines

17、Be careful when add comments to a “switch” expressionswitch var “go” to handle go# If it does not support following value, comment it later: = Wrong!“pause .CommentsComment is set in a shStandard Output & InputI/O operation for standard input and output, normally the terminal in front of us.Print ou

18、t on terminal: puts “abcdefg No Thanks.”Format the string by using “format” commandSimilar as Cset str format “%-2d%20s%9d”, 193 is not equal to 0133;#octal number“193 is not equal to 91”Get input:puts -nonewline “Your name please:”gets stdin sNameStandard Output & InputI/O opeMath and Logical Expre

19、ssionexpr expr expr 1 + 2; set x 10; set y 20; expr $x + $y = 30expr abs(-10) = 10expr 10 * rand() = 9.06197207004855;#result is double , 0 value 5 ;# in range of 07incrset x 1incr x = 2incr x 3 = 5incr x -2 = 3 logic “and” “or” .Math and Logical ExpressionexpControl: Branch and LoopIf . elseif.else

20、.if Boolean expression if xxx else if xxx elseif else Forset sum 0;for set i 0;set y 10 $i 450Whilewhile gets $fd line =0 Switchswitch -exact $xyz “0” ; ?break?;“1” ?default ? Foreach (refer to operation of list)Control: Branch and LoopIf . List, Array & Operation“list” represent a list of stringCom

21、mands for listlist, lindex, lrange, lappend, lreplacesplit, joinArray is similar as the “associate” array or hash data in perl or php.%set lst1 “Jack boy blue Merry girl red”; #or%set lst2 list Red White Yellow Blue%foreach x $lst puts “$xn”%foreach x y z $lst1 puts student name: $x, a $y, who likes

22、 $zstudent name: Jack, a boy, who likes bluestudent name: Merry, a girl, who likes redputs lindex $lst2 2 = Whiteputs lindex $lst2 0 = Red%array set aArr list Jack boy Merry girl%parray aArraArr(Jack) = boyaArr(Merry) = girl%array get aArrJack boy Merry girl%array names aArrJack Merry%array size aAr

23、r2%foreach x y array get aArr puts Name: $x, a $yName: Jack, a boyName: Merry, a girlList, Array & Operation“list” String & Operationappendformatsubststring commandstring comparestring matchstring equal (added in 8.4)string rangestring tolower/toupperstring trimstring comparation: if $str1 = $str2 p

24、uts equalstring comparing commands such as “string match”string class check: string isif string is integer 10 puts okString & OperationappendstringProc and ReturnProcedure in tcl similar as function in C, perl, php, unix shell etc. proc arg1 arg2.args proc body return stringproc calc1 opa “opb 10” r

25、eturn expr $opa + $opb calc1 2 3 = 5calc1 2 = 12 proc calc2 args ;# Vary argument list set opa lindex $args 0 set opb lindex $args 1 return expr $opa + $opb global variableIn a procedure, use “global ” to make a global variable visible from inside of procedureProc and ReturnProcedure in tcFile I/OWr

26、ite file% set fd open abc w+=filef76ec0% puts $fd abcdn% puts $fd efgtn% flush $fd% close $fdRead file%set fd open abc r=filef840d8Get file content line by line% while gets $fd line != -1 puts -nonewline $line=abcd efgtRead commandread ?chunk bytes?set str read $fdwhile !eof $fd svet buf read $fd 10

27、000 .File I/OWrite fileRead fileSocket & File Eventsocket ?-myaddr addr? ?-myport myport? ?-async? host portsocket -server command ?-myaddr addr? portNOTE: “port” specified here is the “listening” port which cant be used to transfer data. As the connection request is accepted, a new socket will be c

28、reated for transport data. 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_P

29、ORT ssif !$status set sock_arr(main) $ss puts Create server socket success. Servers socket is $ss else error Create servers socket failed: $ssproc Echo sock global sock_arrif eof $sock | catch gets $sock line return puts $sock string toupper $lineflush $sockSocket & File Eventsocket ?-myVariable int

30、erpolationHappens in double quote “” and normal expressionsset x “Hello”puts “$x Jack!”set y list $x Jack“!”Interpolation would be prohibited in most kinds of braces puts $x Jack the result would be : $x JackIts not always such thing for brace, brace in some command will not prohibit variable replac

31、ement :catch errforifVariable interpolationHappens Error Handling & DiagnosticMulti-line commandset x list Nanjing Beijing list Shen Yang DalianShould no special character except for carriage-return/new lineShould not put comment after the “catch” commandcatch command catch errors, but would not bre

32、ak the processerror information to be saved as the “errorInfo” global variableStore error information the “error” commanderror command can cause an error, error “line 50 broken for mismatched value”= This error can be captured by “catch” command and return 1, and error string will be set to errorInf

33、o.Error Handling & DiagnosticMulRegular Expression Syntax - Commandsregexpregexp ?flags? pattern string ?match sub1 sub2.? # Get IP address out, and last numberregexp 0-91,3.0-91,3.:digit:+.(:digit:1,3) IP Address: sMatch sVar1regsubregsub ?switches? pattern string subspec varname Regular Expression

34、 Syntax - CoRegular Expression Syntax - BasicMatching charactersMost characters simply match themselvesthe period, “.” ,matches any single characterab matches ab; “a.” match an a followed by any charactor.Character sets a-z matches any character in this rangea-z matches any character isnt in this ra

35、nge, = not matches or Quantifiers * for zero or more: a* matches zero or more as. “.*” matches anything+ for once or more : a+ matches a, aa, aa.a? zero or one: a? matches zero or one aAlternation (or branch)(H|h)ello matches Hello and hello, same as hello|HelloAnchor: matches the beginning of a str

36、ing$: matches to the end of a string: .*$ matches a whole line with anything, even empty lineBachslash QuotingTo turn off special means of following character:. * ? + ( ) $ | Capturing sub-patternsgrouped with parentheses “Im.* IP address (0-9+.0-9+.0-9+.0-9+)$” NOTE: sub-patterns will be captured a

37、nd save in specific variables. If use (?:pattern), pattern will be captured but not saved, command will be fasterRegular Expression Syntax - BaRegular Expression Syntax - Advancedcharacter classes:digit: =0-9=d:alpha: = A-Za-z :space:= bfnrtv =sNongreedy Quantifiers By default quantifier + * ? will

38、match as many characters as possible. Use “?” behind them can prohibit such .+n matches as many lines as possible till last line.+?n matches just one lineBound Quantifiersm,n matches latest m times, and maximum n timesBack referencesNOTE: regsub does not support the function of using back-references

39、 outside of regular expression in perl s/(S+)s+(S+)/$2 $1/Regular Expression Syntax - AdSignalSIGHUPHang upSIGINTInterruptSIGQUITquitSIGKILLkillSIGPIPESIGTERMSIGSTOPSIGTSTPSIGCONTSIGHLDSIGWINCHwindow size changeSIGUSR1SIGUSR2trap call back scripts sig_nametrap puts “bye bye”;exit SIGINTSignalSIGHUPH

40、ang upSIGINTInterTime Event: the after commandproc Circle global switcherif $switcher = off # kill all after event, and then return # do something for repeatafter 1000 Circleafter millisecondsafter ms arg ?arg.?after cancel idafter cancel commandafter idle commandafter info ?id? Time Event: the afte

41、r commandpIntroduction for TkIntroduction for TkCreate children widgetsWindow is organized in a hierarchy A primary window - the root of the hierarchy, is the main window of the application named as “.” . Widgets in primary window are its children window, named as “.”And child window can has its own

42、 children . “.”First charactor of should be in lower-case or a digital numberframe .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.

43、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

44、-command $tTr xview -orient horizontalCreate children widgetsWindow Display Widgets Put and display widgets in main window:.fBut : a Framework contains a single line text input entry.fText : a Framework contains a text will scrollbar.fBut.eEnt : The entryset bBut .fBut.bHello : A buttonset tTr .fTex

45、t.text : Text body.fText.yscroll : X scroll bar (horizontal).fText.xscroll : Y scroll bar (vertical) Three main geometry managerpack : constraint-based geometry managergrid : control in detailplace: place a widget in another onepack .fBut .fText -side left -fill both -expand truegrid .fBut.eEnt -sti

46、cky 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 falseDisplay Widgets Put and displaA Simple Menumenubutton .mb -text File -menu .mb.menu pack .mb -padx 1

47、0 -pady 10 set m menu .mb.menu -tearoff 1 $m add command -label Hello -command puts Hello, World!$m add check -label Boolean -variable foo -command puts foo = $foo $m add separator $m add cascade -label Fruit -menu $m.sub1 set m2 menu $m.sub1 -tearoff 0 $m2 add radio -label apple -variable fruit -va

48、lue apple $m2 add radio -label orange -variable fruit -value orange $m2 add radio -label kiwi -variable fruit -value kiwi note: to add menu in BsPmMonitorGuiA Simple Menumenubutton .mb -tIntroduction for ExpectIntroduction for ExpectExpect Commands Syntax spawnspawn telnet return a pidsave handle in

49、 local variable “spawn_id” sendalias of exp_sendWhen use together with Tk, exp_send is prefer. expectexpect -re “Password:” -re “User Name:” . exp_continue eof timeout interact close exp_internal 0|1 log_file options of “send”-hset send_human .1 .3 1 .05 2set send_human .4 .4 .2 .5 100 send -sset se

50、nd_slow 10,.001timeoutExpect Commands Syntax spawn iuser_spawn_iduser_spawn_idfifoinoutspawn_iduser_spawn_iduser_spawn_idfifoinoutspawn_id No. 1spawn_id No. 2inoutExpectExpectfifoinoutfifostandard I/Ouser_spawn_iduser_spawn_idfifoExample 1: Manipulate MGW automaticallyspawn expect Login:“send “rootr

51、n”expect “Password:” send “rootnr”expect “”send “send 13,1:connectrn”expect -timeout 5 -re “connect.*C”send “helprn”expect timeout 3 “C”spawn expect Login:“ exp_send “rootrn” exp_continue “Password:” exp_send “rootnr” exp_continue -re “” exp_send “send 13,1:connectrn” puts “connect ok” timeout puts

52、“time out” eof puts “session broken” Example 1: Manipulate MGW autoTest Automation with Tcl/Tk and ExpectTest Automation Manul TestTest Simulatoranalyzes traffic/signalingSNMP/CLI/WEMSUTsends traffic/signalingOther EM.Test EngineercontrolscontrolscontrolsTest Management DBfeedback test results and u

53、pdate test statustests to doTest Equipment ( ITE, EAST. )System Under TestElement ManagerTest management Data BaseManul TestTest SimulatoranalyzExample Test ScenarioInstall patchesConfigure SystemSpecific ConfigurationChange Specific configCleanup ConfigurationPatch fallbackInvoke Test ToolVerify re

54、sult?Calling Test ToolVerify result?Pass/FailPass/failExample Test ScenarioInstall pAutomation Simulatoranalyzes traffic/signalingSNMP/CLI/WEMSUTsends traffic/signalingOther EM.Test ScriptscontrolscontrolscontrolsTest Management DBfeedback test results and update test statustests to doTest Equipment

55、 ( ITE, EAST. )System Under TestElement ManagerTest management Data BaseAutomation Simulatoranalyzes tThinking About Automation: MethodsTest HarnessEditorExecutionExecute test scripts in specific flow/sequenceConfigurationStart/Pause/StopStatus monitor : pass/failure TC number and listLogReportCompa

56、tible Test-case language independentAdditional: Test requirement mgmtTest Script and Data MethodLined script -data hardcode with script , script cant be sharedCapture-Playback -data hardcode with script, script cant be sharedShared scriptData-driven (few data drives scripts)Table-driven (huge data d

57、rives same scripts)Try to detach data from scriptsKey-word driven .Thinking About Automation: MetThinking About Automation: Variable TestMulti-Path instead of static/single path Thinking About Automation: VarWhy TclMulti solutions to control equipmentsSocketExpectSNMPSerial port (Dialup) .Many Test

58、Equipment provides Tcl driven API libraryEasy for learning and maintenanceEasy to extendpcap, libnet - Tcl - homebrew Ethernet test APITotally freeWhy TclMulti solutions to contTestCaseScriptLIBFunction LIB:NE Functions.TA Functions.A Example Homebrew Test Framework Data-Driven + Shared ScriptTest H

59、arness Report & Control FunctionsCom LIBSUTTA aTA n Driven DataTest Harness Test Execution Configuration File (e.g a batch file)TA aTestCaseFunction LIB:A ExampleSUR-Switch Utilization ReportSURPurposeSUR is used to collect the utilization of WCS in all sites labIt try to answer following questions about WCS:Switch down

温馨提示

  • 1. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007和PDF阅读器。图纸软件为CAD,CAXA,PROE,UG,SolidWorks等.压缩文件请下载最新的WinRAR软件解压。
  • 2. 本站的文档不包含任何第三方提供的附件图纸等,如果需要附件,请联系上传者。文件的所有权益归上传用户所有。
  • 3. 本站RAR压缩包中若带图纸,网页内容里面会有图纸预览,若没有图纸预览就没有图纸。
  • 4. 未经权益所有人同意不得将文件中的内容挪作商业或盈利用途。
  • 5. 人人文库网仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对用户上传分享的文档内容本身不做任何修改或编辑,并不能对任何下载内容负责。
  • 6. 下载文件中如有侵权或不适当内容,请与我们联系,我们立即纠正。
  • 7. 本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。

评论

0/150

提交评论