书签 分享 收藏 举报 版权申诉 / 52
上传文档赚钱

类型tcltk编程及应用简介课件.pptx

  • 上传人(卖家):晟晟文业
  • 文档编号:4525921
  • 上传时间:2022-12-16
  • 格式:PPTX
  • 页数:52
  • 大小:1.91MB
  • 【下载声明】
    1. 本站全部试题类文档,若标题没写含答案,则无答案;标题注明含答案的文档,主观题也可能无答案。请谨慎下单,一旦售出,不予退换。
    2. 本站全部PPT文档均不含视频和音频,PPT中出现的音频或视频标识(或文字)仅表示流程,实际无音频或视频文件。请谨慎下单,一旦售出,不予退换。
    3. 本页资料《tcltk编程及应用简介课件.pptx》由用户(晟晟文业)主动上传,其收益全归该用户。163文库仅提供信息存储空间,仅对该用户上传内容的表现方式做保护处理,对上传内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知163文库(点击联系客服),我们立即给予删除!
    4. 请根据预览情况,自愿下载本文。本站不保证下载资源的准确性、安全性和完整性, 同时也不承担用户因使用这些下载资源对自己和他人造成任何形式的伤害或损失。
    5. 本站所有资源如无特殊说明,都需要本地电脑安装OFFICE2007及以上版本和PDF阅读器,压缩文件请下载最新的WinRAR软件解压。
    配套讲稿:

    如PPT文件的首页显示word图标,表示该PPT已包含配套word讲稿。双击word图标可打开word文档。

    特殊限制:

    部分文档作品中含有的国旗、国徽等图片,仅作为作品整体效果示例展示,禁止商用。设计者仅对作品中独创性部分享有著作权。

    关 键  词:
    tcltk 编程 应用 简介 课件
    资源描述:

    1、OutlinesTcl/Tk Around UsTcl/Tk OverviewBasic Tcl SyntaxIntroduction for TkIntroduction for ExpectHomebrew Test Automation FrameworkThe SUR of TAO ProjectResourcesTcl/TkAround UsFrom WorkPlaceIn WCS In ITE/8610 Using Expect to communicate with WCS:send CLI commands and get response.In Cisco IOSRouter

    2、enableRouter#tclshRouter(tcl)#puts$tcl_version8.3Test Automation for Telecommunication and Network Equipments To Our Daily LifeIts easy to design handy programs based on Tcl to fulfill different tasks A fish screen save program A e-piano A Painting padFishPIANOTexpict.tclTcl/TkOverview-Say“tickle te

    3、e-kay”Whats TclTcl stands for Tool Command Language Joh Ousterhout,University of California.First release was in 1989.A simple scripting language:Cross platform support.Tcl can run on most popular operation system such as unix/linux,Windows,Macintosh and so forth Scripts are interpreted at run time.

    4、Which makes the development cycle faster than compiled languages,no waiting for long compilations The capability to call C/C+routines Similar to other shell languages such as UNIX C shell,Perl,VB.“”to study Excellent text analysis competenceWhats Tcl(cont)Un-typed and a string-based command language

    5、 Data 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 substitutions All variables are stored as strings.automatic type conversion in contextset x 10;#create a variable“x”and give a val

    6、ue“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 string:-)”puts“Expression result is:$z”;#print result on standard outputs“Y becomes as:”$y”set aArray“Jack boy Merry girl”;#define an arrayputs“Im a

    7、n array,but a string indeed:n$aArray”Whats Tcl(cont)Easy to extend There are numerous free extensions built on top of Tcl/Tk for specific functions available on the Internet.Tclx:Handling signal events Net-Snmp:support snmp communinication BWidget/IWidget etc.:Tk extensions provides special and powe

    8、rful widgets Http&ncgi:for http server programming It is easy to add new Tcl primitives by writing C procedures 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 TkTk A Tcl-based toolk

    9、it for programming graphical user interfaces Quick and easy to build powerful user interfaces.Portable,one copy of script can work unchanged on UNIX,Windows,and the Macintosh.Whats ExpectExpect A Tcl-based Toolkit for Automating Interactive Programs The program interactively prompt and expect user t

    10、o enter keystrokes in response A default command in some operation systems Theres also an Expect extension for tcl which can also be loaded to tcl shellTcl not so good newsInterpreted languages run slower and use more processing time or overheadWithout a complier,syntax errors cant be found until th

    11、e script is executedUn-typed languages do not allow for the most efficient translation of codeBasic Tcl SyntaxTcl Commands FormatA Tcl script consists of one or more commands Commands are separated by newlines or semi-colons A script with two commands separated by a newline character:set a 24set b 2

    12、5 Above 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 words First word is the name of a command Additional words are arguments to that command Words are separated by spaces and tabs var1 var2 VariableNeednt decl

    13、are 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“$”ahead of it as$If you want to app

    14、end 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 methods.namespace procedure To use global to visit global variab

    15、les children interpreterCommentsComment 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-linesBe careful when add comments to a“switch”expressionswitch var“go”to handle go#I

    16、f it does not support following value,comment it later:=Wrong!“pause.Standard Output&InputI/O operation for standard input and output,normally the terminal in front of us.Print out on terminal:puts“abcdefg No Thanks.”Format the string by using“format”command Similar as Cset str format“%-2d%20s%9d”,1

    17、93 is not equal to 0133;#octal number“193 is not equal to 91”Get input:puts-nonewline“Your name please:”gets stdin sNameMath and Logical Expressionexpr 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 1in

    18、cr x=2incr x 3=5incr x-2=3 logic“and”“or”.Control:Branch and LoopIf.elseif.else.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)List,Array&Operation“

    19、list”represent a list of string Commands for listlist,lindex,lrange,lappend,lreplacesplit,join Array 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 n

    20、ame:$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 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

    21、aArr2%foreach x y array get aArr puts Name:$x,a$yName:Jack,a boyName:Merry,a girlString&Operation append format subst string commandn string comparen string matchn string equal(added in 8.4)n string rangen string tolower/touppern string trim string comparation:n if$str1=$str2 puts equaln string comp

    22、aring commands such as“string match”string class check:n string isif string is integer 10 puts okProc 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”return expr$opa+$opb calc1 2 3=5calc1 2=12 proc calc2 ar

    23、gs ;#Vary argument list set opa lindex$args 0 set opb lindex$args 1 return expr$opa+$opb global variable In a procedure,use“global”to make a global variable visible from inside of procedureFile I/OWrite file%set fd open abc w+=filef76ec0%puts$fd abcdn%puts$fd efgtn%flush$fd%close$fd Read file%set fd

    24、 open abc r=filef840d8n Get file content line by line%while gets$fd line!=-1 puts-nonewline$line=abcd efgtn Read commandread?chunk bytes?set str read$fdwhile!eof$fd svet buf read$fd 10000 .Socket&File Eventsocket?-myaddr addr?-myport myport?-async?host portsocket-server command?-myaddr addr?portNOTE

    25、:“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 created for transport data.proc Accept newSock addr port global sock_arrputs Accepted$newSock from$addr port$portset sock_arr(addr,$newSock)list$addr$portfconfig

    26、ure$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:$ssproc Echo sock global sock_arrif eof

    27、$sock|catch gets$sock line return puts$sock string toupper$lineflush$sockExample SERVERExample CLIENTVariable interpolationHappens 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 wou

    28、ld be:$x JackIts not always such thing for brace,brace in some command will not prohibit variable replacement:catch err for ifError Handling&DiagnosticMulti-line commandset x list Nanjing Beijing list Shen Yang DalianShould no special character except for carriage-return/new lineShould not put comme

    29、nt after the“catch”commandcatch command catch errors,but would not break 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”c

    30、ommand and return 1,and error string will be set to errorInfo.Regular Expression Syntax-Commands regexpregexp?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:172.24.229.3 sMatch sVar1 regsubregsub?switches?pattern string s

    31、ubspec varname Regular 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 range

    32、,=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 string$:matches to the end

    33、 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 and save in specific variables.If use(?:

    34、pattern),pattern will be captured but not saved,command will be fasterRegular Expression Syntax-Advanced character classes:digit:=0-9=d:alpha:=A-Za-z :space:=bfnrtv=s Nongreedy Quantifiers By default quantifier+*?will match as many characters as possible.Use“?”behind them can prohibit such.+n matche

    35、s as many lines as possible till last line.+?n matches just one line Bound Quantifiersm,n matches latest m times,and maximum n times Back referencesNOTE:regsub does not support the function of using back-references outside of regular expression in perl s/(S+)s+(S+)/$2$1/SignalSIGHUPHang upSIGINTInte

    36、rruptSIGQUITquitSIGKILLkillSIGPIPESIGTERMSIGSTOPSIGTSTPSIGCONTSIGHLDSIGWINCHwindow size changeSIGUSR1SIGUSR2trap call back scripts sig_nametrap puts“bye bye”;exit SIGINTTime Event:the after commandproc Circle global switcherif$switcher=off#kill all after event,and then return#do something for repeat

    37、after 1000 Circlen after millisecondsn after ms arg?arg.?n after cancel idn after cancel commandn after idle commandn after info?id?Example CLOCKIntroduction for TkCreate children widgetsWindow is organized in a hierarchy A primary window-the root of the hierarchy,is the main window of the applicati

    38、on named as“.”.Widgets in primary window are its children window,named as“.”And child window can has its own 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

    39、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 wordsc

    40、rollbar.fText.yscroll-command$tTr yview-orient verticalscrollbar.fText.xscroll-command$tTr xview-orient horizontalDisplay Widgets 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 entryns

    41、et 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 managern pack:constraint-based geometry managern grid:control in detailn place:place a widget in another onepack.fBut.fText-side left-fill bot

    42、h-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 falseA Simple Menumenubutton.mb-text File-menu.mb.menu pack.mb-padx 10-pady 10 set m m

    43、enu.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-value apple$m2 add radio-label orange-var

    44、iable fruit-value orange$m2 add radio-label kiwi-variable fruit-value kiwi note:to add menu in BsPmMonitorGuiIntroduction for ExpectExpect Commands Syntax spawn spawn telnet return a pid save handle in local variable“spawn_id”send alias of exp_send When use together with Tk,exp_send is prefer.expect

    45、expect -re“Password:”-re“User Name:”.exp_continue eof timeout interact close exp_internal 0|1 log_file options of“send”n-h set send_human.1.3 1.05 2 set send_human.4.4.2.5 100 n send-s set send_slow 10,.001timeoutuser_spawn_iduser_spawn_idfifoinoutspawn_iduser_spawn_iduser_spawn_idfifoinoutspawn_id

    46、No.1spawn_id No.2inoutExpectExpectfifoinoutfifostandard I/OExample 1:Manipulate MGW automaticallyspawn expect Login:“send“rootrn”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_continu

    47、e “Password:”exp_send“rootnr”exp_continue -re“”exp_send“send 13,1:connectrn”puts“connect ok”timeout puts“time out”eof puts“session broken”Test Automation with Tcl/Tk and ExpectManul TestTest Simulatoranalyzes traffic/signalingSNMP/CLI/WEMSUTsends traffic/signalingOther EM.Test Engineercontrolscontro

    48、lscontrolsTest Management DBfeedback test results and update test statustests to doTest Equipment(ITE,EAST.)System Under TestElement ManagerTest management Data BaseExample Test ScenarioInstall patchesConfigure SystemSpecific ConfigurationChange Specific configCleanup ConfigurationPatch fallbackInvo

    49、ke Test ToolVerify result?Calling Test ToolVerify result?Pass/FailPass/failAutomation Simulatoranalyzes traffic/signalingSNMP/CLI/WEMSUTsends traffic/signalingOther EM.Test ScriptscontrolscontrolscontrolsTest Management DBfeedback test results and update test statustests to doTest Equipment(ITE,EAST

    50、.)System Under TestElement ManagerTest management Data BaseThinking About Automation:MethodsTest Harness Editor Execution Execute test scripts in specific flow/sequence Configuration Start/Pause/Stop Status monitor:pass/failure TC number and list Log Report Compatible Test-case language independent

    展开阅读全文
    提示  163文库所有资源均是用户自行上传分享,仅供网友学习交流,未经上传用户书面授权,请勿作他用。
    关于本文
    本文标题:tcltk编程及应用简介课件.pptx
    链接地址:https://www.163wenku.com/p-4525921.html

    Copyright@ 2017-2037 Www.163WenKu.Com  网站版权所有  |  资源地图   
    IPC备案号:蜀ICP备2021032737号  | 川公网安备 51099002000191号


    侵权投诉QQ:3464097650  资料上传QQ:3464097650
       


    【声明】本站为“文档C2C交易模式”,即用户上传的文档直接卖给(下载)用户,本站只是网络空间服务平台,本站所有原创文档下载所得归上传人所有,如您发现上传作品侵犯了您的版权,请立刻联系我们并提供证据,我们将在3个工作日内予以改正。

    163文库