The “cheap hack” method is to use string map: set mapping {} foreach value $trapremlist { # Sneaky point: remove version with leading comma first lappend mapping ",$value" "" $value "" } set removed [string map $mapping $test] This is going to blow up nastily if you've got any of...
It shouldn't be hard. To begin with, you probably want to split the file's contents at the line breaks: set data [split [string trim [read $f]] \n] When you've done that, you could use a number of techniques to select the lines you want, for instance lsearch -all -inline $data...
It looks like you have defined a domain specific language (DSL) with the parsing implemented in Tcl. You may as well use the Tcl parsing itself to deal with things like line continuation and quote handling. The method to do this is to create a safe interpreter and in the...
I'd be really tempted in this case to go with the simplest possible option. set Output [open "Output3.txt" w] set FileInput [open "Input.txt" r] set Desire 174260 while {[gets $FileInput line] >= 0} { lassign [regexp -inline -all {\S+} $line] key x1 y2 z1 if {$key == $Desire} { puts...
python,tkinter,type-conversion,tcl
This is a problem with the way Tkinter guesses the type of a string. In Tcl there simply is no meaningful difference between an empty list or an empty string, so the bytecode compiler can change the internal types at will, just what is most convenient for Tcl in that...
Just remove the foreach. What you want to do is actually this: lassign [split $variable #] net layer border In older versions of tcl where lassign is not available it used to be an idiom to use/abuse foreach: foreach {net layer border} [split $variable #] {} What you were thinking...
If you mean the ampersand, it is not in a tag, it is in the text that appears between two tags. The reason people choose to use XML for data interchange is that it's a standard, and there's lots of software around to handle it. That advantage disappears entirely if...
I simply explored all the children of the tablelist, found the correct label widget reference .t.hdr.t.f.l0 and updated the activebackground property
If you are using the full path of the extension library in both cases, that part should work identically. It probably is doing though; if it couldn't load it, it would generate an error (which might or might not be helpful, as some of the ways that things fail give...
You might want to have a look at the Measurement Protocol API: The Google Analytics Measurement Protocol allows developers to make HTTP requests to send raw user interaction data directly to Google Analytics servers. This allows developers to measure how users interact with their business from almost any environment. Developers...
If you do: exec echo calling a BIG script >@stdout # Everything wrapped around the exec is the same; I omit it for brevity Then the output from the script will be written straight to standard out. However, you lose the ability to read it from your Tcl script. To...
You are allowing the loop to go through at most 1 iteration. This is because return quits the current proc (the loop as well automatically). Fixing that part would give: #!/usr/bin/tclsh proc raise {{base} {pow} args} { for {set base1 $base} {$pow >= 0} {incr $pow -1} { set ans...
You can use seek to move the current location in a channel opened on a file (it's not meaningful for pipes, sockets and serial lines); the next read (gets, read) or write (puts) will happen at that point. Except in append mode, when writes always go to the end. seek...
The variable myvar is a simple variable that is holding the name of another variable. You can use a read from it (with $ or set) anywhere where you'd expect to use the name of the variable: foreach {key value} [array get $myvar] { puts "$key => $value" } What...
The problem is in this code: for {set i 0} {$i < 80} {incr i} { if {$i % 2 == 0} { set cl ($i) [$ns node] $ns duplex-link $cl($i) $clswitch 100Mb 10ms DropTail set tcpAgent [new Agent/TCP] $ns attach-agent $cl($i) $tcpAgent set tcpSink [new Agent/TCPSink] $ns attach-agent $clswitch...
regsub -all -expanded { \( # a literal parenthesis [^(,]+ , # 1 or more non-(parenthesis or comma)s and comma ( [^,]+ , \d+ , \d+ ) # the 3 fields to keep with commas [^)]* # 0 or more non-parenthesis chars \) # a literal parenthesis } $test {(\1)}...
Tcllib has a fileutil module that does a recursive find: package require fileutil set filenames [::fileutil::findByPattern /dir -glob {*.so *.a}] foreach filename $filenames { if {[file isfile $filename]} { set dirs([file dirname $filename]) 1 } } puts [array names dirs] If you want to use this, but can't install something,...
Another approach: % exec cat file -2.55622-3 -0.31-2 -3.225-2 42 foo % set fh [open "file" r] % while {[gets $fh line] != -1} { puts -nonewline "\"$line\"\t=> " if {! [regsub {[-+]\d+$} [string trim $line] {e&} num]} {set num $line} puts -nonewline "$num\t=> " puts [expr {$num + 0}]...
You don't get any output from the test command itself (as long as the test passes, as in the example: if it fails, the command prints a "contents of test case" / "actual result" / "expected result" summary; see also the remark on configuration below). The test statistics are saved...
The thing you're looking for is lrepeat in combination with {*}: set Beam_Gravity_Load [list {*}[lrepeat [expr {$n-1}] $a] $b] You could also do it with for: set value {} for {set i 1} {$i < $n} {incr i} { lappend value $a } lappend value $b set Beam_Gravity_Load $value (If...
To make a procedure that evaluates code in its caller's scope, you need to use the uplevel command inside it. This lets you do what is essentially a macro very easily: proc login {} { uplevel { # Put your code in here, which might look like this spawn ssh...
Since you want to substitute the variables, you can't use {braces} to declare the array elements: $ tclsh % set var1 "some text" some text % set var2 "other text" other text % array set arrValues {1 ${var1}_text 2 ${var2}_text 3 ${var1}_different_text 4 ${var2}_different_text} % parray arrValues arrValues(1) = ${var1}_text...
Either you don't have curl installed on the host that is running your bot, or it isn't on the PATH. Since cron tasks run with a greatly reduced PATH (for various reasons, including security) you'll have to either set up the PATH within your script or use the full name...
One way is to modify your tests to create a "finished" file. This file should be created whether the test completes correctly or fails. Modify the startup loop to remove this file before starting the test: catch { file delete $path0/$testvar/finished } Then create a second loop: while { true...
The easiest way to do this is to walk over the file twice, count how often a line appears the first time and print the unique ones during the second pass as they are encountered. If you have enough RAM (this will take quite a bit), you can use awk...
so this does it: seek [set fp [open $file]] $_fOffset set txt [read $fp] set _fOffset [tell $fp] In context: ::itcl::class clsLogs { private { variable _fOffset 0 } public { method _fFreshRead {file args} { set options(-resetOffSet) false array set options $args if {$options(-resetOffSet)} { set _fOffset 0 }...
You can create a proc to do that (Tcl8.5 and later): proc lunique {l} { set result {} foreach i $l { if {$i ni $result} {lappend result $i} } return $result } For versions before 8.5, you would use [lsearch $result $i] == -1 instead of $i ni $result....
You've probably used a variable containing a numeric value as a command name, perhaps by putting it at the start of a line or by placing [brackets] around it (because brackets do command substitution). The brackets can be even embedded in a string: This example demonstrates what I mean: set...
It turned out the problem is really simple. What I am doing with my scripts is calling them like below: expect script.exp > mylog As told in the description, mylog contains ^M line-endings when opened in Vim or using cat -v mylog. To get rid of them in real-time, I...
You pass variables like this: awk -f some/script.awk -v var="my value" Now you can access your variable var in awk and if you print it, you'll see it contains my value....
When you put braces around an expression, especially when you use variable parts in that expression, Tcl becomes able to determine at script compilation time what the semantics of the expression are. This allows it to generate bytecode for the expression and makes everything rather more rapid when it comes...
It's not that well documented (IMO) but the re_syntax man page says this about greedy/non-greedy preference: A branch has the same preference as the first quantified atom in it which has a preference. (emphasis mine) So if you have .* as the first quantifier, the whole RE will be greedy,...
One solution is to conscript the dict values command: dict values [concat {*}{{a 1} {b 2} {c 3}}] How this works: the dict values collects a list consisting of every other item (starting from the second) in another list. This is intended to be used on dictionaries, but since dictionaries...
You should set the variable as set ciphers "000000010002" Update 2 I don't know whether your additional braces in the array set command is a typo or not. array set IANA_Ciphers [list {0000} {"TLS_NULL_WITH_NULL_NULL"} \ {0001} {"TLS_RSA_WITH_NULL_MD5"} \ {0002} {"TLS_RSA_WITH_NULL_SHA"} \ {0003} {"TLS_RSA_EXPORT_WITH_RC4_40_MD5"} \ [...] {C0AF} {"TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8"} ] } #...
Build example : tar xvf ns-allinone-2.35_gcc482.tar.gz https://drive.google.com/file/d/0B7S255p3kFXNSGJCZ2YzUGJDVk0/view?usp=sharing cd ns-allinone-2.35/ns-2.35/ patch -p1 --ignore-whitespace -i dctcp.patch cd ../ ./install cd ns-2.35/ sudo make install cp ns ns235-dctcp sudo cp ns235-dctcp /usr/local/bin/ Run the simulation : ns235-dctcp simpleDumbbell.tcl .. The files mytracefile.tr 2.1MB, thrfile.tr 10.2kB are created. ( And queue.tr : 0B )....
If your file is smaller in size, then you can use read command to slurp the whole data into a variable and then apply regexp to extract the required information. input.txt data_start 30 abc1 xyz 90 abc2 xyz 214 abc3 xyz data_end data_start 130 abc1 xyz 190 abc2 xyz 1214...
In Tcl 8.6 you can inspect the bytecode to see how such procedures compare. If we define a pair of implementations of 'sum' and then examine them using tcl::unsupported::disassemble we can see that using the return statement or not results in the same bytecode. % proc sum_a {lhs rhs} {expr...
You do not use the correct number of arguments. drawX $rect($i) This is a function call with just one argument. If you want to expand those arguments, you need to use the expand operator on it (8.5+). drawX {*}$rect($i) In older versions that can be done with some eval magic....
The incr command only works with integers. Otherwise, use: set i [expr {$i + $power_pitch}] The for command itself won't mind. (Be aware of float rounding issues; they're not Tcl-specific, but can hit with anything that isn't an integer multiple of a power of 2…)...
Considering your other question, I guess you have to match the lines only if it contains $(eval $(call CreateTest, KEYWORD, I guess you may expect us to literally match the above and then extract the further element needed. input.txt $(eval $(call CreateUvmTest, NOT_keyword, run_test_file1, $(run_test_file.exten) tc_run_test_file.sv $(eval $(call CreateUvmTest, keyword,...
Variables are for storing values. To hide away (encapsulate) some lines of code you need a command procedure, which you define using the proc command. You wanted to hide away the following lines set f [listFromFile $path1] set f [lsort -unique $f] set f [lsearch -all -inline $f "test_*"] set...
If I understand what you're trying to do correctly, wave zoom full works for me. Your technique works if you use WaveRestoreZoom {0 fs} [simtime]. By putting simtime in curly braces, you're asking for it to be treated as a literal string. Square brackets ask it to try to evaluate...
regex,tcl,regexp-replace,regexp-substr
You need to set the variables for the match and captured groups, then you can access them. Here is an example: set a "10.20.30.40" set rest [regexp {[0-9]+\.([0-9]+)\.([0-9]+)\.[0-9]+} $a match submatch1 submatch2] puts $submatch1 puts $submatch2 Output of the demo 20 30 EDIT: You can use regsub and backerferences this...
You could do it like this: proc Section {ID x y} { set ::section_data($ID) [list $x $y] } proc getLoads {ids} { global section_data foreach id $ids { lappend loads [lindex $section_data($id) end] } return $loads } Section 1 20 30 Section 2 25 35 Section 3 30 40 Section...
The bytecode sequence is effectively the same; both push the value onto the operand stack and call the done operation which terminates the procedure successfully. I usually prefer to use return as that's clearer as to what I mean.
You can't do it with arrays or dictionaries; both are mappings from keys to values. Instead, you need to use foreach with a key-value pair system directly: set pairs { set1 table set2 chair set1 chair } foreach {key value} $pairs { puts "$key is $value" } This does actually...
You should use $! to get the PID of the background process just started, accumulate those in a variable, and then wait for each of those in turn in a second for loop. set -m pids="" for vars in $( cat vars.txt ); do tclsh8.5 the_script.tcl "$vars" & pids="$pids $!"...
stored-procedures,tcl,expect,procedure
Oh!!! Poor me. How come I missed this mistake!!! :-D After banging my head for a lot, found that you have used close braces by mistake in the expect statement. -nocase -re "(invalid)|(ambig}" { Changing it to bracket, solves this issue. :-) proc portSec {port} { send "show port interface...
Tcl's comments are real comments, but they're parsed at the same time as other parts of the syntax, such as braces. This means that when we parse your code, we've got to take into account the brace counting as well. Here's how the parser thinks: “Ready to parse a command.”...
It is not the problem with :, but with [. The [ is special to both Tcl and the Expect pattern matcher so it is particularly messy. To match a literal [, you have to backslash once from Tcl and then again so that it is not treated as a...
Square brackets are special in regular expressions as well as Tcl. To match a literal bracket you need to escape it in the regular expression and it needs separate escaping in Tcl. % set match {[} [ % regsub -all $match $cap "" couldn't compile regular expression pattern: brackets []...
You're doing this very thoroughly wrong. What you should do is instead assume that you're passed a widget name (something like .a2.b5.c9) and then ask Tk to tell you what the class of the widget with that name is. winfo class .a2.b5.c9 For an instance of a ttk::entry, this will...
multithreading,bash,tcl,expect,multiple-instances
There are several options to archive this: 1. Execute the script for each hostname: foreach hostname $hosts { exec log.tcl $hostname & } This is like the bash solution. 2. Use threads package require Thread set pool [tpool::create] set jobs {} foreach hostname $hosts { lappend jobs [tpool::post -nowait $pool...
This expect pattern has not matched: expect -re {^(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})\..*$} { puts -nonewline $fileId $expect_out(0,string) set initTime $expect_out(1,string) $expect_out(2,string) $expect_out(3,string) $expect_out(4,string) $expect_out(5,string) } You would know if it did match because you would get a syntax error: the set command takes only one or two arguments, and you have given it...
file exists doesn't support regexp patterns. You can use glob. set myfiles [ glob -nocomplain "/home/ARNE/ARNE/SCRIPTS/*.xml" ] if {[llength $myfiles]!=0} { puts "Following XML files found : " foreach fname $myfiles { puts $fname; # Now you can process these elements as per your wish if {[regexp {RBS_delete\d+\-\d+\.xml} $fname]} {...
The canonical way to do that with Tcl is a so called starpack or starkit. A starpack is a single binary that contains a Tcl runtime and all needed scripts and extensions in a single file. A starkit does it with two files (one runtime originally called tclkit and a...
Variables in Tcl (Tk is just a window drawing toolkit that lives on top of Tcl) are defined when they are written to; there's usually no explicit declaration. The only exception to this is with variables directly in a namespace, where it is best practice to use the variable command...
The way to check if any service is running is to connect to it and ask it to do something trivial (usually either through logging in or doing some kind of no-op). If that fails, the service is down, and if it succeeds, you've got a connection you can use...
The problem is because of \*. The backslash will be translated by Tcl, thereby making the \* into * alone which is then passed to expect as expect * As you know, * matches anything. This is like saying, "I don't care what's in the input buffer. Throw it away."...
reference,tcl,expect,evaluation
If you have a string containing just the name of a variable, you are best off using set with only a single argument: set myref {expect_out(buffer)} puts "The value is [set $myref]" But if you've got that $ as well, the right thing to do is to use subst (which...
You should check for the value you specify: you have 10.77.33.200 in the string, and 10.77.34.200 in the regex. Also, pay attention to .: to match a literal dot, you need to escape it. Here is a working code that finds both values: set buff "SOME TEXT o=India-SIPUA 6264 0...
The package provide command goes in the definition code of a package to declare that a particular package with a particular version has been defined. Here's a trivial example: namespace eval ::foo { proc bar {} { puts "this is the bar procedure in the foo namespace" } } package...
crange has a slightly extended syntax for the index expressions. If you don't need that syntax (and you probably won't) you should use the core command string range instead since it lets you avoid the dependency on TclX and makes your code more readable to people unfamiliar with the extension....
The short answer is to look at the value of errorInfo which will contain the stack trace. The more complete answer is to look at the catch and the return manual pages and make use of the -optionsVarName parameter to the catch statement to collect the more detailed information provided....
Do not think it is a bug, as stated in documentation: reference here [3] Words. Words of a command are separated by white space (except for newlines, which are command separators). [4] Double quotes. If the first character of a word is double-quote (“"”) then the word is terminated by...
I don't know if the Tcl interpreter in your system is recent. If it is, you should be able to use python $python_app_name {*}$python_app_args to get the arguments as separate strings. The {*} prefix is a syntactic modifier that splices the items in a list as separate arguments. Example: list...
In Tcl, we can use regexp to extract the required data. set nmap_output "Nmap scan report for 169.254.0.1 Host is up (0.014s latency). Not shown: 97 closed ports PORT STATE SERVICE 80/tcp open http 1720/tcp open H.323/Q.931 5060/tcp open sip Device type: VoIP adapter|WAP|PBX|webcam|printer" if {[regexp {scan\s+report\s+for\s+(\S+).*Device\s+type:\s+([^|]+)} $nmap_output match ip...
It's a common design choice in Tcl (as well as some other languages). When a command like dict get (or, more commonly, open) fails, the program has to deal with it, which means it has to be alerted to the failure in some way. The most common options is to...
I don't have my copy of "Exploring Expect" handy, but I think you're running into a variable scoping issue. spawn invisibly sets a variable named spawn_id. When you call spawn in a proc, that variable is scoped only for that proc. Declare it as global: proc sftp_connect {} { global...
The gets command waits for newline. It's probable that both outmsg.data and opphandle ends in newlines ("\n" or "\r" or "\r\n"). It would explain why the first two gets works. Check to see if inmsg.board ends in a newline. If not, you can simply do: fprintf (write_to,"%s\n",inmsg.board); For robustness, it's...
I solved this issue in this way : proc unzip_file_if_needed { fileName } { if { [file extension $fileName] != ".gz" } { return $fileName; } set tmpDir [fileutil::tempdir] set pId [pid] set tmpFileName [ file join $tmpDir pId ] set unzipCmd [ file join $tmpDir [ append pId "cmd.sh"...
break should work. The expect man page has this to say in the documentation for the expect command: Actions such as break and continue cause control structures (i.e., for, proc) to behave in the usual way. I'd write your loop like this: foreach host $data { # very basic data...
I have found an answer (courtesy of Greg Snow enter link description here sorry for answering my own Q, but editing was impossible through misplaced error calls "you're text appears to contain code blablabla" whilst I correctly designated it (cntrl K). here's the code define.test<-function(){ # create a function to...
Tcl does not do substitutions on things inside {braces}. If you want substitutions, you've got to either put the overall word inside "double quotes", or use the subst command: set x 2. set columnLine [subst {$x 5. 10. 15.}] set x 2. set columnLine "$x 5. 10. 15." One advantage...
It's a misfeature really, and one that isn't going to be fixed. The issue is that a six (or more) digit number can be interpreted as either a number or as a timestamp or a time or a date. The parser (something horrible hacked from the output of yacc) gets...
You can emulate a zip function with lmap: % set a {1 2 3} % set b {4 5 6} % lmap x $a y $b {list $x $y} {1 4} {2 5} {3 6} % puts [join [lmap x $a y $b {list $x $y}] \n] 1 4 2...
Code to generate a sequence of unique random numbers could be written like this, but it won't work unless $nnums is less than or equal to $rmax. set nnums 30 set rmax 20 set nums {} if {$nnums > $rmax} { puts "You can't get $nnums unique values from a...
As Etan Reisner pointed use double quotes in the puts command instead of braces, so that it will get replaced. puts ${file_id} " root_image=node-${env(os1)} if {[string first r ${env(os1)}] == 0} { create_node_byid 1 [string range ${env(os1)} 0 4]-64 } else { create_node_byid 1 [string range ${env(os1)} 0 5]-64 }...
The manual page for entry, specifies that the -readonlybackground option will change the background color for entry widgets in read-only mode.
A Perl one-liner to slurp the whole file and match across any newlines for the pattern you seek would look like: perl -000 -nle 'm{(foo2).*(\#89888)}s and print join " ",$1,$2' file The -000 switch enables "slurp" mode which signals Perl not to split the file into chunks, but rather treat...
The most compact way is probably: string length [regsub -all {[^2]+|2{2,}} $a {}] But there's more to this. Measuring the frequency of an item in a list is trivial: set freq {} foreach item $list {dict incr freq $item} The resulting dictionary will have items for keys and their frequencies...
All Itcl variables are mapped to Tcl variables in a namespace whose name is difficult to guess. This means that you can get a callback whenever you read a variable (it happens immediately before the variable is actually read) via Tcl's standard tracing mechanism; all you need to do is...
Method 1 : With simple string commands, we can get the desired result. set input {Hello1.my.name.is.not.adam.go.away, Hello2.my.name.is.not.adam, Hello3.my.name.is.not.adam.leave.me noobuntu dinesh} foreach elem $input { # Getting the index of the word 'adam' in each element set idx [string first "adam" $elem] # If the word is not available, then 'idx'...
I'd write this: set min_key 0.1 set max_key 0.3 set fid [open Data_1.dat r] while {[gets $fid line] != -1} { lassign $line a b if {$a == $min_key} { set min $b } if {$a == $max_key} { set max $b } } close $fid set fid [open Data_2.dat...
The exec command considers it a failure if the called command outputs anything to stderr, even if it has a successful exit status: If any of the commands writes to its standard error file and that standard error is not redirected and -ignorestderr is not specified, then exec will return...
There is a lot that seems problematic in your code. In the first line, you use the variable lenght. Tcl doesn't care about spelling, but if you don't have such a variable (you might possibly have a length variable instead) you will get an error. In the invocation expr ([lindex...
With glob, you can apply the pattern and can get the list of file names matching our criteria. puts [ exec ls -l ]; #Just printing the 'ls -l' output set myfiles [ glob -nocomplain hello*091*.txt ] if {[llength $myfiles]!=0} { puts "Following files matched your pattern : " foreach...
In the book, it is given without spaces only. Running this we will the get the following errors. % if {$x > 2}{ extra characters after close-brace % set greater true true % } invalid command name "}" % ...
python-3.x,tkinter,tcl,tk,python-module
This might not be an exhaustive answer, but it can be helpful. It is probably because your tcl/tk version does not contain a subpackage called treectrl, from the following error: _tkinter.TclError: can't find package treectrl The wrapper library you are using TkTreectrl for tkinter has this statement somewhere: ver =...
When subst attempts to perform substitutions on the text you gave it, it needs an existing variable with a matching name. If no such variable exists, subst throws a TCL LOOKUP VARNAME exception. How to catch that? You can catch the exception after subst has failed as usual, with catch...