Updated 2015-09-01 18:20:42 by pooryorick

How to post on Ask-pages edit

This page is not intended for new questions.

This page is here for historical reasons. Eventually, the wikignomes will split it up, placing the information present here on the appropriate pages.

For asking new questions, see Ask, and it shall be given # 12 (or whatever is the newest in the series).

Questions edit

upload files

I have a script which runs from a shell to upload files to a server, currently using FTP - which works fine. Now because of changes on the shell (can't use FTP any more) I have to use SFTP. This is is the code which is giving me problems:
 set pipe [open "|sftp $server" w+]
 fconfigure $pipe -blocking 0 -buffering line -translation crlf -eofchar$
 set rep [gets $pipe]
 set rep [gets $pipe]
 putlog "......... $rep ............"
 puts $pipe "$pass"
 puts $pipe "put $localfile $remotefile"
 puts $pipe "exit"
 close $pipe

This code works fine with FTP but with SFTP the password prompt goes out to the console and the pipe "$pass" never gets sent to SFTP - why is that? I realise that using SSH RSA is the easiest way to do this, however the shell doesn't permit it. Any suggestions? Thanks in advance :)

Lars H: First, I suppose "the shell" in "the shell doesn't permit" typically refers to the server you're connecting to rather than the actual shell you run.

The reason it doesn't help to write the password to the pipe is that SSH takes care to use the terminal rather than stdin for this. Might be a security enhancement, or perhaps just to be helpful for scripts (no need to have code to deal with prompts). You might be able to get around this by setting the SSH_ASKPASS environment variable, but as I understand it that isn't used as long as there is a terminal to talk to.

One solution might be to use Expect.

Another solution might be to use the -M and -S options of ssh to first open a master connection (which asks for password) and then run the actual file transfers as slave connections (that simply join the established master connection).

Also, is there a reason you don't use scp? As long as you only want to copy a file (or several), it should be quite sufficient, and can be run using exec directly. There might be some issues with filename quoting if you're using odd characters, but I suspect sftp has similar issues. Scp might be too weak if you have particular needs regarding file permissions, though.

threads and tk

AW can anyone help me with threads and tk? Or if another way exists to do what I want, that's fine too. Problem: I want to make a UI which shows a changing value. Getting this value requires starting an external process (and waiting for it to end), and this takes a short while (say, a second). Current implementation: using 'after', a shedule execution of a proc which calls the starts the external process and waits, then reshedules itself after x seconds.
  proc t { } {
    #call other executable
    after 5 t

Result: every 5 seconds, all of the UI is blocked for a second (VERY annoying). My attempt at fixing this: do the external process in a thread. But I can't get threads to run under tk. This works in tclsh, but not in wish:
  package require Thread
  catch {console show}
  set ::gThread [thread::create {thread::wait} ]
  puts "created thread $::gThread"
  proc test { } {
    puts "test starting"
    thread::send -async $::gThread {puts [clock seconds]}
    after 2000 test
    puts "test ending"

  puts "started first test"

  vwait forever

under tclsh (doing 'tclsh d:\testthreads.tcl' at the command line) it results in:
  created thread tid000014E8
  test starting
  test ending
  started first test
  test starting
  test ending


under wish (doing 'wish d:\testthreads.tcl' at the command line) it results in:
  created thread tid00001444
  test starting
  test ending
  started first test
  test starting
  test ending
  test starting
  test ending

etc. The clock numbers are not printed, the thread is not running. But why??? (Note that under wish, the vwait forever at the end makes wish hang, even after you close all the windows, it remains running!)

ABU 13-mar-2007 ***Using not-registered COM objects***

I need to deliver my tcl-app; it includes some special COM objects driven by tcom. Of course, before using my app, COMponents should be registred on the new PC, and this is the first step towards the DLL-Hell ...

I've read an interesting article Simplify App Deployment with ClickOnce and Registration-Free COM [1] and made some experiments with Tcl ... it works !! (no need to recompile anything or change your tcl-app) The bad news is that this solution forces you to add a .manifest to the Tcl Interpreter (wish.exe ?) and this is not in general a good idea.

I think (I'm not an Internal-Windows programmer) this should be a job for tcom or a similar package. I wish tcom were able to load COM-objects just by reading some kind of manifest files ....

Do you think is it possible, or can you suggest an alternative ?

binding <Return>

Barry 9 March 2007: Hi, I'm getting stuck binding <Return> to several entry widgets so that action will occur with the widget that is altered.
 set x 0
 while{1} {
 if {z1 == z2} {
   entry .e$x -text $text

   bind .e$x <Return> {lset listitem [.e$x get]}

   incr x

Problem is, if a 2nd match to the if is found the bind selects the last entry created, not the one containing the cursor

EMJ 13 March 2007 - You have put your bind command in braces, so nothing in it is substituted until the binding is fired - at which point x has it's highest value, so the last entry is used. You need the substitution to happen when the binding is defined, so you could do
 bind .e$x <Return> "lset listitem [.e$x get]"

but it is usually safer to make the bind command a proc whose arguments are the things that need substituting at definition time:
 proc entrtn {ent} {
   lset ::listitem [$ent get]
 bind .e$x <Return> [list entrtn .e$x]

another Tk window pops up

LES on Feb 26 2007: In my Tcl/Tk apps, whenever another Tk window pops up, like an error or open/save dialogues, after it is closed, the main window gets that "hey look at me" blinking in the task bar and the title bar becomes greyed out - what my Linux window manager marks as a window without focus. That doesn't seem to happen to other applications, like Tkcon. It really seems that I am supposed to do something to prevent that, but I have no idea what it could be.


MG Feb 26 2007 - I'm trying to use the ftp package from Tcllib for some automated FTP tasks, but I've run into a few problems. There doesn't seem to be any (obvious) way of checking a) whether a given path exists, or b) whether a path refers to a file or a directory. And it seems, from the quick digging I've done, that this is something lacking from the FTP specs, not from the Tcllib package. All I can see that would be some help is the results of ftp::NList - which seem to be server-specific, and not follow any specific format. Can anyone offer any help or suggestions? Thanks in advance, Mike

canvas / screenshot

Feb 13th 2007 (KBH) I've read how to Capture a window into an image, and have used image's "-format window" option to save a screenshot of a canvas. However, is it possible to save just a section of a canvas? Ideally, I'd like to be able to limit the capture with a set of coordinates in the canvas's coordinate system. Is there a simple way to do that? - RS: Like this?
 set im1 [image create photo -data $canvas]
 set im2 [image create photo]
 $im2 copy $im1 -from $x0 $y0 $x1 $y1
 image delete $im1

read pipe

Is it possible to start a TCL Interpreter which will keep running, read and interpret commands from a pipe and return all output via the pipe? I have already implemented something similar, where the tcl interpreter opens a server socket and processes received commands via eval, but someone asked me this stupid question about pipes, and i can't provide an answer. [fh]-feb 6


I was wondering if someone could take a look at my script and tell me what I could do to make it work and/or optimize it. Its the first thing I've ever written in tcl, and im not sure about how things should go in the debugging stage. tcl-dicebot is based on picoIRC 0.2 script written by RS. modified so that the gui aspects are removed.

It's meant to be a stand-alone IRC bot that waits for users to type messages starting with *d* (ex: 1d20) and then generate a random number based on that starting string (in the case of 1d20, a (1-20)random number once.)

I've had a lot of trouble getting the irc parts of the script to work, even when they arent modified... Can anyone else get it to connect to irc.sorcery.net 9000 and join #omen-heart? My attempts have failed. Nor can I get pico to do it. Any and all help is appreciated davou-jan 31,8:20pm


[rahul] 1/17/2007

hi everybody, I have problem in loops like, can i pause loop for every certain gaps. here is i am trying but noe successful example:
 set var 3
 for {set i 1} {$i < 12} {incr i} {
 set rvalue [expr int($i *1000.000)/1000.000]
 set r1 [expr int(($rvalue/$var) *100)/100]
 if { [string is integer $r1] } {
 tk_messageBox -message "pause"
 tk_messageBox -message "here is i=$i"

To get to some of the machines I work on, I have to login in through a gateway. Since my password on the gateway and target machine is the same, I have an expect script that accepts my password (with echoing turned off, of course), uses the password to login to the gateway, talks through ssh to the gateway to login on the target machine using the password a second time, then goes into interact so I can do what I need to on the target machine.

This works great, except that when I do an "ls -l" in a large directory or anything that puts out around 80 or more lines of text, my session goes into an infinite loop, listing the text over and over.

Is anyone else aware of interact sometimes losing its mind like this, is it something I'm doing, or does anyone know of a fix for this problem? Thanks in advance...

tpb 2006-10-19

LES Dec 10, 2006

I was wondering if it is possible for a Tcl/Tk application to generate false key events that would surely be detected by the system but not really sent/produced in the application. My idea is to frustrate key loggers.


TCOM experts?

On Win XP, I want to simulate a drag and drop, via code, to a given application via COM objects. This has to simulate dragging an object (an image file) to a running instance of the applicaton. As if a tif file were dragged on to a running copy of Photoshop, for example, or some other graphic app. Whatever Explorer is telling the application when the drag/drop is done to its live window--I want to tell it via a command line. I realize this will likely require me to build some sort of drop object, including the file name. Does anyone have any fragments of code that can point me in the right direction?

- Daniel B. 10/19/06

Itcl / classes

GWM (Sep 12 2006) I'm using Itcl and have several classes which inherit from a basic class. If I have an instance of the derived class then I can use [$instance info inherit] to find if it inherits from thebase class. I can also use [itcl::find classes] to find all classes; how do I find all classes which inherit from the baseclass (I want to exclude the itcl classes which dont inherit from the baseclass)?

file mtime

September 9th, 2006 [Eugene Chang]: Please help me with the following: I am using Windows XP Service Pack 2 and I get an error when doing [file mtime $new $dir]. Does setting the mtime only work for files?

MG When I try and change the modification time for a directory, I get a "permission denied". Is that the problem you had? (It's [file mtime $file $time], btw - you have the new time and the file/dir args the wrong way around above.)

LV I see the same thing as MG:
 (lwv27) 12 % file mtime mytest 0
 could not set modification time for file "mytest": permission denied

(and when I click on that error, I get:
 could not set modification time for file "mytest": permission denied
    while executing
 "file mtime mytest 0"
    ("uplevel" body line 1)
    invoked from within
 "uplevel #0 {file mtime mytest 0}"

The following questions have had some degree of answer provided edit


GWM how can I embed a tk_chooseColor (dialog) in another window? In particular I want to extend the colour picker to define both colour and transparency by adding a slider to the choosecolor window. I might also want to extend even further to set a colour for one of the OpenGL material attributes (diffuse, ambient specular and emissive colours can all be different in OpenGL).

MG On Windows, a native colour picker is used. Probably the easiest way to do it is to use the pure-Tcl/Tk one used on other platforms, which seems to be in tcl/lib/tk8.4/clrpick.tcl for me. If you copy the code out of that, you can customize it as much as you need, embed it into other windows (or other windows into it, to add your extra controls) and do pretty much anything you need. Then call that instead of the real tk_chooseColor.


(DB) on Wednesday February 28th 2007: I have a simple, almost silly question. n the app I am working on, I need to insert the name of the file that is going to be saved as. Let me be more precise. The command is: Save as. In the File name rectangle, no file name appears at the moment. I'd like to put in this File name rectangle the name of the file I am on (the one that will be saved with another name). How do I go about it? Thanks!

RS Have a look at tk_getSaveFile. It is most simply called like this:
   set filename [tk_getSaveFile -initialfile default_filename]
   if {$filename ne ""} {
      #... save content to $filename
   } else {# user canceled the save selection}

(DB) Thanks (RS), week-end projecteer extraordinaire!

select text with mouse

(DB) on Wednesday February 28th 2007: Yet another question. I'd like to code a function that would do the following: the user will select a range of lines with the right click of the mouse. He would do a block in other words. Afterwards, when he'll click on Sort, the selected lines will be sorted by alphabetical order or by numerical order. Any suggestions for coding such a function? Thanks again!

RS Here's a sketch that I tested to work - make sure you understand how it works, what it does :^)
 proc tsort {w} {
   foreach {from to} [$w tag ranges sel] break
   if ![info exists from] return
   set lines [split [$w get $from $to] \n]
   $w delete $from $to
   $w insert "$from - 1c" [join [lsort -dic $lines] \n]

(DB) Thanks again (RS)! I'll analyze your code line by line to make sure I understand it.


(DB) February 24th 2007 As soon as the user clicks on an hyperlink, I'd like the program to verify if the user has modified the page or not. If so, if the page has been modified, a box will appear and ask him to save or not to save. How do I go about it? How can I tell if the user has entered a character or not? Thanks in advance.

MG I think if you want something along these lines:
  set ans no
  if { [$textWidget edit modified] } {
       set ans [tk_messageBox -message "Save changes?" -type yesnocancel]
       if { $ans == "yes" } {
  if { $ans != "cancel" } {

(DB) This sounds pretty OK. Thanks so very much MG!

***arrays like C* (DB) February 24th 2007 Yet a second question. Does Tcl have arrays like the C language? I am talking specifically of reading a database and keeping the appropriate data in arrays. Does/Can Tcl proceed this way also?

MG Tcl does have arrays, but they're a little different from C arrays. There are some pages on the wiki already explaining the differences, and how Tcl arrays work - the array page is probably the best place to start out. But, in their most basic form:
 % set myArr(foo) bar
 % set myArr(baz) boing
 % puts "foo is $myArr(foo) and baz is $myArr(baz)"
 foo is bar and baz is boing
 % parray myArr
 myArr(baz) = boing
 myArr(foo) = bar

At least some of the Tcl extensions for working with databases provide mechanisms already for retrieving results from the db and putting them straight into a Tcl array, so it would be worth checking the docs for whichever you're using.

Tcl 8.5's dicts may be of some use to you, too. I've never used them myself, though, and am not entirely sure what differences/benefits/etc they provide over arrays, so they may not be :)

(DB) Well I'll try them both. Thanks again MG for the valuable information.

Lars H: Don't forget lists -- being indexed by an integer, they're the closest Tcl analogue of C vectors/arrays.

As for arrays vs. dicts, the main difference is that a dict is a value, but an array is a variable.

  • You can put dicts as elements in a list, array, dict, etc. or pass them by value to a command. In order to do something similar with an array, you effectively need to convert it to a dict first (using array get).
  • You can put traces on elements of an array, but not on the elements of a dict.
  • Elements of an array are valid in most places where a command wants a variable (e.g. scan and regexp). There is no corresponding syntax for an element of a dict, so you'll need to use the dict command explicitly for accessing these.

LV Check to see if the database of interest provides any natural relationship for you. If not, perhaps discuss with those supporting the tcl binding for the database whether something like you are envisioning might be implemented - sort of tie for Tcl...

remember position

(DB) February 21st 2007 I am trying to code a function that would register where the user has left from when he clicked on a link so that he would go back to this particular part of the start page when he clicks Home. As for example: he clicks on a link called: [My Sql] located on the bottom of the page. He then edits the page and he goes back to the start page (the page he has left from, the page where the link was located). The bottom of the start page will be shown. How do I code such a function? Not easy! Thanks in advance for anything that would put me on track.

CJL needs to know what the browser in question is. Firefox exhibits the required behaviour if the 'back' button is used, and any other path back to a page returns the user to the top, which feels correct to me. But of course that has nothing to do with Tcl... If the browser in question is implemented on a Tk canvas, then keeping a record of URLs and last known values of yview (and maybe xview?) should be trivial.

(DB) There is no browser. It is a stand-alone editor that does hyperlinks on a local level. Not on the internet.

CJL : "It is a stand-alone editor..." written in pure Tcl/Tk? Without a more precise definition of it, guessing an answer is going to prove tricky.

MG Assuming you're using the Tk text widget, when the user clicks your hyperlink (which in this case would be a <1> binding on a text-widget tag), you need to have the proc include the coordinates of the character clicked. Then your proc which takes them back can jump to that point. For example...
 pack [text .t -width 40 -height 5 -yscrollcommand ".s set" -wrap word] -side left ; pack [scrollbar .s -command ".t yview"] -fill y -side right
 .t tag configure foo -foreground blue
 .t tag configure normal -elide 0
 .t tag bind foo <1> {doStuffWith .t [.t index current]}
 .t insert end "this is normal text\n\n\n\n\n\nn\n\nnormal text " normal
 .t insert end "hyperlink" [list normal foo]
 .t insert end " more normal text\n\n\n\n\n\nmore text" normal

 proc doStuffWith {w index} {
  $w tag configure normal -elide 1
  $w tag configure goback -foreground blue
  $w tag bind goback <1> [list goBackTo $w $index]
  $w insert end "This is temporary text displayed because you clicked at $index. When you're done reading this, " tmp
  $w insert end "go back." [list tmp goback]
 proc goBackTo {w index} {
  eval \$w delete [$w tag ranges tmp]
  $w tag configure normal -elide 0
  $w mark set insert $index
  $w see $index

The $widget see $index line is the one which scrolls the widget so you can see the place where they clicked the hyperlink, and the index to go to is passed all the way through the process, from where they first click to the end, where it returns to that spot.

If that's nothing like what you're doing, though, then more info would really be needed, as CJL says, before anyone can really offer more help.

(DB) This seems very OK. It's what I needed. I'll try it. Thanks so very much for your help, MG.

network client

[MPE] February 3rd 2007.

I am tearing my hair out with a TCL problem I am experiencing. The application is a network client. Intermittently, the application locks up, runs at 99.9% CPU (top) and strace-ing the PID shows no output at all - not even a blocking system call. I believed for a while this might be to do with load over the network interface causing problems in the event loop, but recently this has been disproved as the issue occured with only a couple of people on the system. Previously, it had only shown up with high load and a large number of concurrent clients running.

I would be very grateful for some assistance in identifying the right place to look for a solution or workaround to this issue.


CJL responds, A socket closed by the other end will cause a client to 'see' a fileevent, which if not handled properly will lead to 100% cpu usage. Maybe that's it? Run this example (of how not to do it) in a 'wish', then do 'telnet localhost 12000', then disconnect. Proper handling of the situation is described on a page around here somewhere.
  proc readable { ch } {
    while { [gets $ch buffer] != -1 } {
        puts "Client said : $buffer"

  proc server { ch addr port } {
    puts "Connection from $addr:$port"

    fileevent $ch readable [list readable $ch]

  socket -server server 12000

edit on this wiki

(MZ) January 29th 2007.

When using the edit on this wiki, I notice that I cannot retrieve back text I have deleted when I hit Undo. Each character of the old text appears one after the other, one at a time. Why so? Why can't I get the whole text back? Is there a bug?

Lars H: I presume you're accessing the wiki over the Web. Then you don't actually get the wiki involved in the editing until you click the "Save" button; everything up to that happens inside your web browser. Hence it is probably the web browser that only undoes one character at a time.


JM 1/20/2007

I just installed the libpgtcl1.5 in my linux PC, the folder contains three files:

  • libpgtcl1.5.so
  • pgtcl.tcl
  • pkgIndex.tcl

doing "package require Pgtcl" is not working, even that the auto_path variable includes the path to these files, I am a Tcl novice but I notice that the tcl files are basically empty, there is nothing but comments, and I was expecting to see some "package provide" stuff. could someone give me a hint?

MG The pkgIndex.tcl (check the case of the filename, btw - some packages in the past have been distributed with 'pkgindex' or 'PKGINDEX', which doesn't work) should contain a line somewhere along the lines of...
  package ifneeded Pgtcl 1.5 [list source [file join $dir pgtcl.tcl]]

  package ifneeded Pgtcl 1.5 [list load [file join $dir libpgtcl1.5[info sharedlibextension]]]

There should be (the equivilent of) a 'package provide Pgtcl 1.5' somewhere, but it could be done by the .so when it's loaded. One way to test if it's a problem with the package or with your auto_path is to do something like this...
  cd /path/to/pgtcl/package
  set dir [pwd]
  source pkgIndex.tcl
  package require Pgtcl

If it finds the package OK after doing that, your auto_path is most likely the problem. Otherwise, the package could be missing a file or something like that.

JM thanks, looks like a file is missing, I just tried writing the 2nd line suggested to the pkgIndex.tcl, then I got the following message:
 % package require Pgtcl
 couldn't load file "/usr/local/atcl/lib/pgtcl1.5/libpgtcl1.5.so": libpq.so.4: cannot open shared object file: No such file or directory

libpq.so.4 ?

LV That would be the name of the PostGres library. Sounds to me like a real mess - the binary is linked against some version of postgres and the creator just figured anyone who wanted the binary would already have the original database library.


[naveen] 12/1/2007

hi i had earlier asked some questions about a script that calculates runtime. the script which i wrote is pretty lengthy; moreover it has some flaws in it. i.e: if i start my run on a month end then i'll be in a fix to decide how much time has elapsed (if the run completes in next month beginning), as i'll have to consider many parameters like leap year,no of days in that month etc..

do you have any suggestions so that i can make my script to work round the clock without any problem!

i saw the material about date and time on http://wiki.tcl.tk/948 . but there is no such example which shall give the time difference.

i am trying to develop a script which can give the difference between 2 dates eg.
 Thu Jan 31 09:13:41 IST 2007 # the time i start my run
 Thu Feb 01 09:23:44 IST 2007 # the time my run finishes

now i need to get the difference in time in hours:mins:secs

i.e my output shall be

The total time taken for this run is x hours: y minutes:z seconds

please do help me with the same....


The command clock scan timestring returns the number of seconds since some fixed day. Example:
 % clock scan {Thu Jan 31 09:13:41 IST 2007}

The command clock format seconds converts the number of seconds to a date. Example:
 % clock format 1170215021
 Wed Jan 31 04:43:41 W. Europe Standard Time 2007

Btw January 31, 2007 is not on Thursday.

LV Check out [2], which discusses calculating time between two dates.


DF asked the following question on other pages ([3] and [4])


All I want to do is to launch a simple TCL program from C++ code. Is there a simple example or step by step instructions on how to do this? My second application is to pass data from an array into the TCL program. Any help would be appreciated. Thanks DF

LV Do you mean launching a program like execlp("abc.tcl", "arg1", "arg2", (char *)0);?

Invoking Tcl from C++

Hello Robert (directed towards [5]), I really could do with some help in invoking a simple Tcl prog from C++. Is this possible? I have been through all the relevant web pages but there is not one page which simply describes how to do it withough out going into geek speak. Can you help? Thanks

RLH I know nothing about C/C++ at the moment sorry.

LV Would you mind explaining, in different words, specifically what it is that you are trying to do? Launching a simple Tcl program is done the same way that you start any program in C or C++. There is nothing unique about Tcl in this regard.

Generally one uses a C or C++ call such as fork and execlp, or system, to tell the operating system to start a program. Of course, perhaps on Windows there are other calls one has to make - you've not told us what operating system you are using yet.

If you are just wanting to exec a Tcl program, you won't be able to pass in an array - you can pass a fixed number of arguments (often a small number), OR, you could write a file containing the data and have your tcl program read and interpret the data in some fashion.

Why not take a step back and tell us what it is that you are wanting to accomplish after the program is written, and let us see if we can provide you pointers on how to write code to reach that goal?

GWM perhaps you want to add to your C/C++ program something like this which loads a Tcl interpreter into your program, then evaluates a script with Tcl in it.
  int cballoon (ClientData cd, Tcl_Interp *interp, int argc, char **argv)
  { // this routine is executed in response to a button...
        int i;
        fprintf(stderr,"Hoo this is C ok\n");
        for (i=0; i<argc; i++) fprintf(stderr," %d %s",i,argv[i]);
        return TCL_OK;
  int myAppInit(Tcl_Interp *interp)
        int status = Tcl_Init(interp);
        int status = Tcl_Init(interp);
        if (status != TCL_OK) { return TCL_ERROR; }     /**/
        status =Tk_Init(interp);// add Tk options
        if (status != TCL_OK){  return TCL_ERROR;}
        Tcl_StaticPackage(interp, "Tk", Tk_Init, (Tcl_PackageInitProc *) NULL);
        Tcl_CreateCommand (interp, "balloon", (Tcl_CmdProc *)cballoon,  NULL, NULL);
        //Tcl_EvalFile(interp, "simple.tcl"); // if you want to load a script file.
        Tcl_Eval(interp, "button .inc -text \"from C\" -command \"balloon 2 76 ferret\"");
        Tcl_Eval(interp, "pack .inc -side left -expand 1");
        /* here we do any other initialisation, add new functions which will be called as & when needed....*/
        /* here we do any other initialisation, add new functions which will be called as & when needed....*/
        return TCL_OK;
  int main(int argc, char ** argv)
        Tk_Main(argc,argv,myAppInit); // Tcl_Main calls myAppinit when it is ready.
        return 1;

Read the manual for details of linking C procs to script commands as in the proc cballoon above. Preferably use the Tcl_Obj versions as they are faster (but less obvious hence my use of char **argv form). As mentioned above, use fork or execlp to launch as a separate program (these functions are the same under Windows & Linux ??And Mac??).

[naveen] 9/1/2007

p.s i have removed the script. if anyone needs the same plz mail me @ [email protected]

hi i wrote a script for runtime calculation. it was working fine for other start time and endtime values. but i got this error when i executed it. [ plz see the timing below].could you please tell me how i can set it right? here the time is 09 hrs, but i guess my Tcl script is trying to read the same as octal. can i do some declaration so that it can be read as an integer?
 09:13:41 #start time
 09:23:44 #end time

 Error: expected integer but got "09" (looks like invalid octal number)
        Use error_info for more info. (CMD-013)

runtime.txt has the following data
 Thu Jan 11 09:13:41 IST 2007
 Thu Jan 11 09:23:44 IST 2007


After splitting the time string, you got a string hr = 09. Leading zeroes are interpreted as octal numbers, not decimal numbers. Solution:
 % set hr
 % set hr [string trimleft $hr 0]

Now, you can calculate with the decimal number 9. - RS Warning: string trimleft trims as much as it can:
 % string trimleft 09 0
 % string trimleft 00 0

returns an empty string, which is bad to do calculations with. scan however returns a valid integer:
 % scan 09 %d
 % scan 00 %d

[naveen] 9/1/2007

hi to my previous question you had provided the following answer:

could you please explain the program in brief? i couldn't figure out few commands. i have commented on the same. i am extremely sorry for the inconvenience caused.
 proc cat file {
    set p [open $file r]
    set contents [read $p]
    close $p
    set contents

 set doneList {}
 set max -

 foreach {word1 word2 word3 num} [cat data.txt] {
    if {[lsearch $doneList [list $word1 $word2 $word3 $num]] < 0} then {  ;# does this write strings that match to doneList ??
        lappend doneList [list $word1 $word2 $word3 $num]
        if {$max eq "-" || $num > $max} then {                            ;#why have we used $max == "-" here
            set max $num

 puts "done:\n[join $doneList \n]"

 puts "maximum area is $max"

please explain the entire program in brief. Thanks for the Nth time for your support and help...

MG In the if/lsearch, it checks to see if the line from the file has appeared before. If the line hasn't appeared (ie, if the lsearch returns -1), the code adds the line into $donelist, then checks to see if the number is the highest so far.

The variable $max is set to "-" before the foreach starts. So, if $max is still set to "-", you know that you're running the loop for the first time (so whatever $num is, it's definately the highest number you've seen so far - because it's the only number you've seen so far).

Hope that helps.

read from Bluetooth

Anton 8/1/2007

I have a Bluetooth USB adapter. How can I read data that is sent to PC through this adapter?

LV Shouldn't it be the same way you would read data sent to a PC through any means?

[naveen k n] 8/1/2007

Error: value '' for option '<range_value>' not of type 'float' (CMD-009)

could you please explain what i have to do to correct such errors?

Answer First reproduce the error, then input "puts $errorInfo". The variable shows the function call trace.

[naveen k n] 8/1/2007

hi, thanks for the Tcl code you came up with. i am a beginner in Tcl. ur site has been extremely resourceful. i have another request.

question:i need to source few Tcl files till a variable becomes zero:

eg: say a is my variable. i derive the variable a from another Tcl file

i need to do the following function
 source xyz/abc/reduce.tcl
 source def/ghi/time.tcl

could u guys please help me out with the same. thanks a ton in advance..!!

 set a 1

 foreach file {
 } {
    if {$a == 0} then exit
    source $file
    puts "a is $a"


2006-01-06 [gg] - I looked on the wiki already and could not find an answer (also did some other research). I am working on a commercial piece of software which should be available as shareware and activateable using license keys (the shareware version would have a license key which expires on a certain date, the non-shareware version would have a license key which expires after a year or so).

The thing is, of course there is the danger of multiple users making use of the same license key - even when a license server based model is used, since files could be copied. So, the solution is: unique computer IDs.

Question: how can I, in a cross-platform compatible manner (i.e. pure-Tcl) or at least supporting *NIX and Windows, generate unique computer IDs which will not change (best would be if they cannot be manually changed, but I don't think that this would be an issue)?



LV Tcl doesn't have a function like that built in. However, on Linux at least, there should be a command similar to the unix "hostid" command which supposedly returns something like this to you. Check for its source code and see if it might be possible to turn that into a Tcl extension.

[naveen k n] 5/1/2007

hi , i need a piece of Tcl code with the following functions:

1]it must read a file in which data is dumped eg:lets say a file /usr/temp/area_report.txt has the following data
 the area is 100
 the area is 100
 the area is 100
 the area is 60
 the area is 60
 the area is 60
 the area is 10


2]i need to read the data only once. ie i want to delete the repeated lines in the report so my new report shall be
 the area is 100
 the area is 60
 the area is 10

3]i need to extract the max value out of the report and set it to a variable

 set max_area = 100

it was easy fopr me to achieve the same in shell using sed & awk. but i need to do the same in Tcl. please do HELP me with the same. Thanks in advance!!!

 proc cat file {
    set p [open $file r]
    set contents [read $p]
    close $p
    set contents

 set doneList {}
 set max -

 foreach {word1 word2 word3 num} [cat data.txt] {
    if {[lsearch $doneList [list $word1 $word2 $word3 $num]] < 0} then {
        lappend doneList [list $word1 $word2 $word3 $num]
        if {$max eq "-" || $num > $max} then {
            set max $num

 puts "done:\n[join $doneList \n]"

 puts "maximum area is $max"

Tcl procs

wdb 03 Jan 2007 On my Emacs, the speed bar can show me all Tcl procs made with proc and Tcl methods made with method, but neither self-defined xproc nor fully qualified ::snit::method with arguments differing from Itcl.

Is there any explanation on the web or elsewhere how to manage this on the fly (i. e. without learning elisp)?

LV Tcl doesn't have a method built-in. Certain itcl has them, and I suspect that snit, xotcl and several others do. So that doesn't really tell us what you are using. I don't know what an xproc is. Check with the snit mailing list about ways to see its methods.

[Aditya] 29 Dec 2006

While trying the following code, i am getting this error. Please advise if i am missing something.
 % package require http 2.5
 % http::geturl http://www.google.com/
 couldn't open socket: connection timed out

2006-12-30 [gg] - I do not get that error. The code appears correct to me. I recommend saving the output of the command anyway, because otherwise the command will have been useless (save the result and then call ::http::data $result to obtain the actual HTML).

You should check if you can access that URL using a browser. Maybe your internet access is crippled?

MG Check and make sure your firewall is set up to allow wish/tclsh to access the internet, too.

2007-01-02 [gg] - And if your browser is set up to use a proxy like HTTP or SOCKS.

LV 2007 Jan 02 - try http://www.tcl.tk/ or some other well known and working web site. Are you able to access any site from your program?

[GreenAsJade] 24 Dec 2006

I'm having problems with packing in an iwidgets::scrolledframe. The "-fill" doesn't seem to be being obeyed:
 package require Iwidgets
 namespace import -force iwidgets::*

 scrolledframe .sf -relief raised -labeltext "test" ;# comment me out
 set frm [.sf childsite]                            ;# comment me out

 #set frm [frame .sf]   ;# uncomment me to see the right behaviour
 label $frm.lab -text "Enter name:"
 entry $frm.ent
 label .but -text "below"
 pack $frm.lab  -side left -fill x
 pack $frm.ent  -side right
 pack .sf -fill x -expand yes
 pack .but

If you comment out the scrolled frame, and instead use a normal frame (by uncommenting that line) you will see the two different behaviours.

How can I get the "normal frame" behaviour in a scrolled frame?


MG Jan 3rd 2007 - It looks like the Iwidgets scrolledframe works by embedding a frame widget in a canvas (and then scrolling the canvas). And, while your label is filling the frame, the frame isn't filling the canvas (and from looking briefly at the canvas command's docs, there doesn't seem to be a way to make it do so). You can see that by giving the widgets all bg colors:
  $frm.lab configure -bg orange ;# label
  $frm configure -bg blue ;# frame
  [winfo parent $frm] configure -bg green ;# canvas

I'm pretty sure there are other scrolledframes around that work differently, though - maybe one of those will allow the fill you want.

[Ben] Dec, 20 2006

Hello! I have a problem with my embedded tcl interpreter. I would like to issue a warning to the user if he has done something which may be incorrect. However I currently am struggling to find out how to issue a linenumber with my warning. If I flag an error I can get the line number from the interp->errorInfo variable however that stops the execution of the script. Is there anyway to get the line number without stopping execution?

Thanks in advance. Ben


Dec 19, 2006

Where is autoconf? I try to build an extension using TEA on winXP, but I need autoconf to do so. Why is that not included in msys_ming8, which I can find on tcl/sourceforge. I downloaded the autoconf-package and this needs perl! Am I wrong? I don't want to install perl and all this instead I really need to do so. Thanks.

LV autoconf is not a tcl program. It is one of a series of GNU programs designed for determining system configuration info. If you don't have it, your choices are:

  1. Locate and use a binary version of the package you are wanting to build
  2. check to see if someone has already packaged all the relevant dependencies pieces relating to autoconf for your OS/hardware
  3. start downloading and building pieces that you need.

See http://www.gnu.org/software/autoconf/ for literally the autoconf package. However, I don't know what additional packages you might need - perhaps m4, perl, maybe automake or libtool. These are all a part of a suite of programs commonly used for code and Makefile generation.

console comment entry field

[EMC] Dec 19, 2006

What's the easiest way to provide a console comment entry field? I would like the user to add a comment when inside the console (no need for GUI) and this returns back to my script so I can append it to a README file. Thanks.

LV I was confused by this question. An entry field is a GUI widget. You said, in parens, there was no need for a GUI. So what is it you really want to do? Are you really wanting to get some input from the user? If so, you could do something like
 puts -nonewline stdout "Enter your comment now: "
 gets stdin comment

[EMC] Jan 12, 2007 Thanks for the response. When I execute tclkit-win32.exe in windows I see a console window and a grey blank gui box. When my script is running I would like it to ask for my comment as you show above. Problem is, it does not wait for the user to enter the comment. The script finishes and another command line prompt % is given in the console.

LV I don't know how well stdin and stdout work in a Windows based Tk console. Check over in the stdin page to see what you can find.

[Gattu] Dec 1, 2006

I'm using special characters , and in my program. If I edit the program code directly in the database manually, it works fine. But when I import the program from the file, these characters are replaced. I also tried to use [format %c 164] in the program to avoid the character replacement, but even this did not work. Can anyone please help me? Thanks.

Richard RS has documented most facets of that here on the wiki. Start with Unicode and UTF-8 and Unicode file reader.

print a variable

WK Nov 24, 2006 - How do I print a variable to my local printer? Can Tcl display the Windows "Print" dialog box? Can you give me an example? Thank you.

2007-01-02 [gg] - read the printing wiki page


MG Nov 8 2006 - In the docs for the Img package's handling of MS Windows Icons (ICO), it says: The format name ico is recognized by the option -format. In addition the value for the option is treated as list and may contain any of the special options listed in section ICO OPTIONS. That section mentions -index <int> and -verbose <bool> as the new options. Just using
  image create photo imgName -format ico -file myicon.ico -index 3

returns an error, though (unknown option "-index") The only thing I could think of that the In addition line there could mean was
  image create photo imgName -format [list ico -index 3]

which isn't right. Does anyone have any experience of using these extra options, or can understand the help text better than I do and explain it? Thanks in advance for your help.

2007-01-02 [gg] - I know nothing about the Img package, but one thing I notice about that second attempt of yours is the fact that the appears to be no -file option specified.

Minimal Console

JM in a Minimal Console Richard left some homework when he says "this can be expanded with colors to distinguish stdin/out/err, an entry with a history, menus (see Menus made easy), whatever.

it is probably very simple, but, how can I distinguish between stdin/out/err? ...or, just give me a hint.thanks.

HE You can find an answer on a Minimal Console now.

[Ben] wed 1 Nov

Hello, I am interested in writing c commands to extend the tcl parser I have embeded in my application.

  • I have various c++ objects in my program which are identfied by name.
  • I would like to write a function which takes a tcl regular expression and matches object names based on this regular expression.
  • I am using Tcl_EvalFile to run the commands in a file through the tcl parser.

My problem is that by the time the tcl object reaches one of my functions it has already had the backslash substitution performed on it. So for example if the user had typed ball\. this would become ball. so when I pass this string to the tcl regular expression engine it would match ball[any char] instead of ball. Does anyone know how to prevent this backslash substituion occuring. I have searched the web and looked at the code for regexp and am none the wiser. Any help would be great! (p.s many thanks to all the contributors to this wiki page it has already helped me out a lot.)

Edit - Actually I realised that I was not correctly bracing my regular expressions to protect them from the tcl parser. However is it possible to modify the tcl parser so that it "knows" about regular expression and does not perform standard substitutions on them but instead performs substititutions with its own set of rules distinct from the tcl standard???

Lars H: Short answer: No, that's not possible. Long answer: If you really hack the Tcl core you might be able create something to that effect, but don't do that. The uniform substitution rules, combined with the ease with which you can prevent substitutions (99.9% of the cases just wrap it up in braces), are important parts of what makes Tcl such a radically simple language that still can exercise the power of all sorts of little languages.

[Ben] The languages I have used before all have complicated syntaxs like perl or c because of this I was initially worried by the effect detailed above. However from the links you provided I can see that a lot of thought and effort have gone into this "radically simple" approach.

Thank you for your answer. Ben.

(13 October 2006) Thanks to the person who started this new Ask and it shall be given page. However, we start a new page in April usually (for spring; spring = renewal). But I understand # 4 got too big already so you had to break the tradition.

I have a little problem with the following algorithm. I am trying to create a file that would hold all the deleted text a user deletes during a session. Why? Because the Undo in my editor is very unreliable and I'd rather delete the Undo function. I believe the Undo function is mainly useful to retrieve deleted text. This is why I want to have the above programmed.

Anyone has a clue as to the algorithm needed to create a file with deleted text?

MG Sounds like the real solution would probably be to fix your undo code - assuming you're using a text widget in 8.4 or above, support for undo/redo is built in. But if you take a look at the bindings for <Delete> and <BackSpace> in the text widget, they show you what text will get deleted. Basically, you want something like:
  text .t
  bind .t <Delete> {copyDeleted %W Delete}
  bind .t <BackSpace> {copyDeleted %W BackSpace}
  proc copyDeleted {w key} {
    if { [$w nextrange sel 1.0 end] ne ""] } {
         doSomethingWith [$w get sel.first sel.last]
       } elseif { $key eq "BackSpace" } {
         if { [$w compare insert != 1.0] } {
              doSomethingWith [$w get insert-1c]
       } elseif { [$w compare insert != end] } {
         doSomethingWith [$w get insert]

where doSomethingWith is a proc that prints its arg to a file. (Not tested, but something along those lines should work.) Though that won't really help you with undoing anything, since you'll just get a whole mess of deleted text all strung together (though it could be made more complete to include where text was deleted from and when). (Oh, and it won't include text deleted because of overtyping, either, but you could check the text-widget binding for KeyPress and factor that in). Reworking your undo code is probably a much simpler (and more effective) solution, though, IMHO.

Thanks a lot! Since the editor saves automatically, the Undo unsaves; also since it hyperlinks, undoing a hyperlink is deleting the text in a page. All these functions get in conflict with each other when I click Undo and the program simply goes out after deleting the contents of a page. Not a good thing! I believe the best would be to take out the undo button. Unless you see a way to undo just the text and not the hyperlink and the saving functions. A sort of filtered Undo.


Anonymous: i have a file in which the data is of the format

-root MOD -parameter NUM_COUNTERS 2 -parameter NUM_COMPARES 4 -parameter TBEXT_UNIT 1 MOD -revised

I need to take all the integers in various variables and also need to take

-root MOD -parameter NUM_COUNTERS 2 -parameter NUM_COMPARES 4 -parameter TBEXT_UNIT 1 as one parameter and MOD -revised as another parameter..

Can someone help me out ?

pcam It is nice to sign messages, or tell who you are. My attempt (although you need to explain a bit more than that)
    # supposing you have a fixed number of variables
    set myVarList [list var1 var2 var3 var4 var5]
    set line "-root MOD -parameter NUM_COUNTERS 2 -parameter NUM_COMPARES 4 -parameter TBEXT_UNIT 1 MOD -revised"
    foreach val $line {
    if {[regexp {[0-9]} $val]} then {
    lappend myVarList $val
    lappend myVarList [lrange $line 1 [expr [llength $line] - 3]]
    lappend myVarList [lrange $line [expr [llength $line] - 2] end]

Note: the regexp test is really weak, I assumed your input does not have a mix of digit and chararcters This is far from optimal, but should give you a starting base.

thread starting on 3sep2006

problems with Refrigerator magnetic Poetry, fairly well solved , thanks, closing out section-goldshell7.

Can someone delete page Refrigerator_Magnetic_Poetry from the current system.http://wiki.tcl.tk/16037 I found out "Magnetic Poetry" is a trademark, so I'm starting a new page called Refrigerator_Pinyin_Poetry. thanks, goldshell7.23Sep2006

LV we can't delete pages on the wiki - just blank them out.

running a Tcl interpreter in a sub-thread

(Hans-Albert Schneider, Sep 22 2006): We are running a Tcl interpreter in a sub-thread (this thread is not created with Tcl methods), and we have replaced the "exit" command to do some application specific stuff. The main thread passes strings to the sub-thread, which in turn calls Tcl_Eval() on them. Now consider a file containing the following lines:
  puts "Hello"
  puts "Still there"

If that file gets sourced, both "puts" commands are executed. What must we do so that the interpreter stops after the exit command? (If the "exit" is the last command, all works as expected, so the basic stuff is in place.)

Tcl_Exit() is not an option, as it calls exit(), and we are experiencing crashes if exit() is called in a sub-thread. So I tried Tcl_Finalize(), but this leads to a crash when the second "puts" is to be executed (if I understand correctly what I have found so far on the web and in the docs, Tcl_Finalize() has cleaned up stuff that is needed by the "puts" to (re)open the output channel).
 The solution (Hans-Albert Schneider, Dec 22 2006):

This seems to have been a tough one; nobody replied :-)

We are now doing essentially this (in C/C++; actually, it's Qt that does it for us):
    pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL);
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);

Mike Stout 9/26/05

I've built a simple circuit board with 680 ohm limiting resistors in series with 1.4V LEDs and connected that to GND and a data channel on the parallel port. I've tried both versions of lpttcl on my IBM thinkpad laptop and can't seem to get any digital outputs to go low. The lights are always lit (i.e. the data is always high) when I'm attempting to control the parallel port outputs through tcl. When I boot up the computer, the lights flicker on and off in a determined fashion, so I think the board works just fine. With lpttcl version 3, the base address always becomes -68 (decimal) and not 0x3BC or something sensible. I checked the bios and my parallel port is set for bidirectional. I tried to use the version 1 of the software, but didn't see any changes.

Any ideas? Also, two pics on the "Applying the parallel port to drive a LED..." webpage aren't visible. Namely the schematic (kind of important if I'm supposed to be connecting something I'm not) and pin layout (not important, I found that just fine).

Any help would be appreciated!

Cheers, Mike

Updata 10/1/06 I figured out what was wrong... several things. For some reason the base address of the parallel port always came up as something crazy like -68 decimal. I had to manually set it to 0x3bc once I forced the BIOS to assign the port to that address. Also, I was tinkering with the port settings and accidentally did not have it in BIRECTIONAL mode. Once I set it back to this mode, things were nearly cool. I then realized that I had wired the ground to the connector chassis and not pins 18-25. So in quick summary...
 CKT:  Data port to 1k resistor to LED to pin 18-25 (all are ground)
 LPTTCL: lpt_setba 0x3bc , lpt_wrctrl 0 , lpt_wrdata 0x00 to 0xff

Cheers, Mike

2006-08-28 thema

What's the difference between
  uplevel #0

  namespace inscope ::

Lars H: namespace inscope adds a level to the the context stack (you can [uplevel 1] out of it), whereas uplevel #0 goes back to an already existing level in the stack (thus hiding everything that was added to the stack afterwards).

I am stumped. I am writing a test to simulate a user checking out of an online store. The store is in beta so I have been using www.fao.com as a model, since they will be very similar. The problem is this: I cannot, for the life of me, get TCL or tclwebtest to recognize the buttons.... AHhhh!!

Here is an example of the code from the fao page (since it is public and I can share it):
 <div id="atc"><input name="submittag" class="formbutton" onclick="javascript:setAddTo(1, personalization)" value="Add To Cart >>" type="button"></div>

and the URL I got it from is:


Basically, all I need is to push the button and have the cart have the item in it. ***ANY*** advice would be greatly appreciated. My thanks in advance.

- Austin A

Lars H, 13 Oct 2006: From the look of it, that web site seems to rely on the browser having a built-in javascript interpreter. That seems to make the issue of using Tcl for testing a bit tricky... Presumably one should have to handle the exact javascripts sent by the server just like a browser would do, for the test to make sense. (Had the aim instead been to have Tcl talk to the server, one could have ported the javascripts to Tcl instead and handled it that way.)

Lars H, 14 March 2007: Selenium sounds as if it's meant for this kind of thing.

Active Script

The Active Script page needs updating. I'd do it but I'm actually in need of the information it could supply. There's a \[Provide relevant URLs to define and further discuss this area\] and MHo has already annotated it with "any additional examples or links to any documentation???" The company I work for wants me to convert their language to an Active Script aware one. Where do I start???

BMA 2006-11-06

fr see tclcontrol and [6] for HTML and VB examples


gjs The language on my PC is set to English, and all TCL apps think that it is German, I have tried different builds and versions of tclsh and wish. Is there a way to correct this?

LV I'm not certain, but I think that tcl gets its idea of the language to use from an environment variable. Ask over in the wiki's chatroom or on comp.lang.tcl to get more info.

file selection dialog

tb How can I use the unix file selection dialog with windows? The one that comes with windows doesn't browser vfs.

CJL - The script version of the file dialogs works with vfs (but is ugly) - see near the top of tk_getopenfile

tb - Thanx! - Ugly or not, it hast to work :)

MG Also see the page on a File selection dialog for Tile, which includes (presumably native-looking, as it's Tile) selection dialogs which can work with a vfs.

read image data from RAM

HI , I am creating a command for Tk in C to read a image data from RAM and display it on Screen. The image data is in Binary format.Actually i had finished in Tk but was not optimized.. So any suggestions regarding this?

SO i have gone through creating commands.... And i have read the Bin data into an Array. How can i reperesent that to be manupilat as Image..... Read too much But confused;) Any suggestions or references would be Appreciated..

Can reach me by Email to:[email protected]