2014-09-24 26 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