2014-09-24 78 views
1

我打开一个shell程序,用tcl打开命令,shell输出文件有一些stings和tcl命令逐行。可以在任何告诉我如何,如果该行是一个Tcl命令从Tcl运行其他程序读取文件

我用下面的sytnax打印如果行是字符串以及如何评价的列表,但它试图EXCUTE琴弦也

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 } 

}

回答

1

你可以试试这个(测试)

原理:每一行的第一个单词测试,看它是否属于已通过“信息被首先获得了TCL的命令列表, 命令”。

有时您无法正确获取第一个单词,这就是为什么此命令在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" 
    } 
} 
+0

谢谢Abenhurt,上面的代码工作。我需要先在tcl中打印行,然后执行tcl命令。 – user3069844 2014-09-24 16:34:14

+0

+1。我对你的代码有一些评论,所以我添加了一个社区维基答案。 – 2014-09-24 18:03:09

1

充分感谢abendhurt。重写他的回答到更地道的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" 
    } 
} 

注:

  • 使用while {[gets ...] != -1}减少代码位。
  • 使用split将字符串转换成适当的名单 - 不再需要catch
  • 使用内置in操作以提高可读性。

我想我明白:

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 ;] 
+0

谢谢glen jackman,我需要下面的waay ex:myfile可能有lin1:AAAA lin2:BBBB lin3:cmd1 lin4:CCCC ,,,, so on print output :: AAAA BBBB cmd1 CCCC ,,,,执行tcl_cmd :: eval cmd1 – user3069844 2014-09-24 20:38:58

+0

我不明白。评论中缺少格式。请更新您的问题。 – 2014-09-24 23:53:39

+0

输入文件(字符串和命令的组合): AAAA #text BBBB #text CMD1#EVAL Tcl命令 DDDD #text CMD2 ..... TCL输出: AAAA BBBB CMD1 DDDD cmd2 .... 评估:cmd1 评估:cmd2 评估:... – user3069844 2014-09-25 06:50:50