Main Content

Running external processes in Tcl and Tcl/Tk

Archive - Originally posted on "The Horse's Mouth" - 2006-06-29 11:06:20 - Graham Ellis

If you want to run external processes from a Tcl based program (Tcl, Tcl/Tk, expect), there are various ways of doing it.

Firstly, the whole purpose of the Expect extension is to allow you to control other processes via its three major commands of spawn which starts another process, send which sends characters to that other process, and expect which causes your program to wait until it gets a particular response, or one of a series of possible responses.

If you don't need to go to these lengths, though, there are three other options at least.

You can use an exec command to run an external process and capture the result returned in a variable:

set ff [exec ls]
puts $ff


You can use the open command and open a process by preceeding it with a "pipe" character in place of its default behaviour which would be to open a file. This lets you handle a process that generates a lot of output line by line, and by using r+, w+ modes and flush you can also set it up for both read and write. Here's a simple example of opening a piped process for read:

set fh [open |df r]
while {[gets $fh line] >= 0} {
puts $line
}


Finally, you can talk to a remote process via the network, using socket to open a remote connection. Like the open command, the socket command opens a channel so once the channel is set up you can handle the data stream exactly as if it was a file or pipe. Again, don't forget flush. Example (getting a file off a web server):

# Through a socket - a remote process

set fh [socket 192.168.200.66 80]
puts $fh "GET /index.html HTTP/1.0\n"
flush $fh
while {[gets $fh line] >= 0} {
puts $line
}