Reputation: 23
I am opening a shell program from tcl with open command, the shell output file has some stings and tcl commands line by line. Could any tell me how to print if the line is a list of strings and how to evaluate if the line is a tcl command
I used the following sytnax, but it is trying to excute the strings also,
set fileID [open "| unix ../filename_1" r+]
while 1 {
set line [gets $fileID]
puts "Read line: $line"
if {$line == "some_text"} { puts $line #text
} elseif { $line == "cmd"} {set j [eval $line] #eval cmd }
}
Upvotes: 1
Views: 107
Reputation: 246807
Full credit to abendhurt. Rewriting his answer into more idiomatic Tcl:
set fid [open myfile]
set commands [info commands]
while {[gets $fid line] != -1} {
set first [lindex [split $line] 0]
if {$first in $commands} {
puts "tcl command line : $line"
} else {
puts "other line : $line"
}
}
Notes:
while {[gets ...] != -1}
to reduce the code a bit.split
to convert the string into a proper list -- no longer need catch
in
operator to improve readability.I think I understand:
set fid [openopen "| unix ../filename_1" r]
set commands [info commands]
set script [list]
while {[gets $fid line] != -1} {
set first [lindex [split $line] 0]
if {$first in $commands} {
lappend script $line
}
puts $line
}
eval [join $script ;]
Upvotes: 1
Reputation: 620
You can try this (tested)
Principle : the first word of each line is tested to see if it belongs to the list of tcl commands, which has been first obtained by "info commands".
Sometimes you can not properly obtain the first word, that's why this command is in a catch {}.
set fileID [open myfile]
set cmdlist [info commands]
while {1} {
set readLine [gets $fileID]
if { [eof $fileID]} {
break
}
catch {set firstword [lindex $readLine 0] }
if { [lsearch $cmdlist $firstword] != -1 } {
puts "tcl command line : $readLine"
} else {
puts "other line : $readLine"
}
}
Upvotes: 1