Io 从Tcl运行其他程序读取文件

Io 从Tcl运行其他程序读取文件,io,tcl,Io,Tcl,我正在用open命令从tcl打开一个shell程序,shell输出文件中有一些sting和tcl命令。有没有人能告诉我,如果这行是字符串列表,如何打印,如果这行是tcl命令,如何计算 我使用了下面的sytnax,但它也尝试执行字符串 set fileID [open "| unix ../filename_1" r+] while 1 { set line [gets $fileID] puts "Read line: $line" if {$line =

我正在用open命令从tcl打开一个shell程序,shell输出文件中有一些sting和tcl命令。有没有人能告诉我,如果这行是字符串列表,如何打印,如果这行是tcl命令,如何计算

我使用了下面的sytnax,但它也尝试执行字符串

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 }
}

您可以试试这个(已测试)

原则:测试每行的第一个字是否属于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"
    }
}   

完全归功于阿本赫特。将他的答案改写成更加地道的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"
    }
}   
注:

  • 当{[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 ;]

谢谢Abenhurt,上面的代码正在运行。我需要先打印tcl中的行,然后执行tcl命令。+1。我对你的代码有一些评论,所以我添加了一个社区wiki答案。感谢glen jackman,我需要以下示例:myfile可能有lin1:AAAA lin2:BBBB lin3:cmd1 lin4:CCCC,,,,等等,打印输出::AAAA BBBB cmd1 CCCC,,,在执行tcl_cmd::eval cmd1I后,我不明白。注释中缺少格式。请更新您的问题。输入文件(字符串和命令的组合):AAAA#text BBBB#text cmd1#eval tcl command ddddd#text cmd2。。。。。TCL输出:AAAA BBBB cmd1 DDDD cmd2。。。。评估:cmd1评估:cmd2评估:。。。