如何防止tcl脚本退出?

时间:2019-07-05 08:55:55

标签: tcl

我正在运行tclsh some.tcl,遇到eof后退出。我希望它不退出,并控制用户交互。 请注意,我们可以通过调用shell和采购脚本来做到这一点,但这不能解决我的问题,因为它不能用于自动化。

1 个答案:

答案 0 :(得分:1)

如果您可以加载TclX package(旧的但仍然有用),则可以执行以下操作:

package require Tclx; # Lower case at the end for historical reasons

# Your stuff here

commandloop

这非常类似于Tcl自己的交互式命令行的工作方式。


否则,这是一个脚本版本,可完成交互式命令会话的大部分操作:

if {![info exists tcl_prompt1]} {
    set tcl_prompt1 {puts -nonewline "% ";flush stdout}
}
if {![info exists tcl_prompt2]} {
    # Note that tclsh actually defaults to not printing anything for this prompt
    set tcl_prompt2 {puts -nonewline "> ";flush stdout}
}

set script ""
set prompt $tcl_prompt1
while {![eof stdin]} {
    eval $prompt;                        # Print the prompt by running its script
    if {[gets stdin line] >= 0} {
        append script $line "\n";        # The newline is important
        if {[info complete $script]} {   # Magic! Parse for syntactic completeness
            if {[catch $script msg]} {   # Evaluates the script and catches the result
                puts stderr $msg
            } elseif {$msg ne ""} {      # Don't print empty results
                puts stdout $msg
            }
            # Accumulate the next command
            set script ""
            set prompt $tcl_prompt1
        } else {
            # We have a continuation line
            set prompt $tcl_prompt2
        }
    }
}

正确处理剩余的位(例如,加载Tk包时与事件循环的交互)将需要更多的复杂性...