【问题标题】:Reading a file from Running other programs from Tcl从运行其他程序从 Tcl 读取文件
【发布时间】:2014-09-24 13:57:07
【问题描述】:

我正在使用 open 命令从 tcl 打开一个 shell 程序,shell 输出文件逐行包含一些 stings 和 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 }

}

【问题讨论】:

    标签: io tcl


    【解决方案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"
        }
    }   
    

    【讨论】:

    • 谢谢 Abenhurt,上面的代码可以正常工作。我需要先打印 tcl 中的行,然后执行 tcl 命令。
    • +1。我有一些关于你的代码的问题,所以我添加了一个社区 wiki 答案。
    【解决方案2】:

    完全归功于 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 ;]
    

    【讨论】:

    • 感谢格伦杰克曼,我需要以下方式,例如:myfile 可能有 lin1: AAAA lin2: BBBB lin3: cmd1 lin4: CCCC,,,,so on print output::AAAA BBBB cmd1 CCCC,, ,, 执行后 tcl_cmd::eval cmd1
    • 我不明白。 cmets 中缺少格式。请更新您的问题。
    • 输入文件(字符串和命令的组合):AAAA #text BBBB #text cmd1 #eval tcl command DDDD #text cmd2 ..... TCL输出:AAAA BBBB cmd1 DDDD cmd2 ....评估:cmd1 评估:cmd2 评估:...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2013-06-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多