如何防止 tcl 脚本退出?
How to prevent tcl script from exiting?
我是运行 tclsh some.tcl
碰到eof就退出了。我希望它不退出并将控制权交给用户进行交互。 请注意,我们可以通过调用 shell 和采购脚本来完成此操作,但这并不能解决我的问题,因为它不能用于自动化。
如果您可以加载 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 包时与事件循环的交互)需要更多的复杂性...
我是运行 tclsh some.tcl
碰到eof就退出了。我希望它不退出并将控制权交给用户进行交互。 请注意,我们可以通过调用 shell 和采购脚本来完成此操作,但这并不能解决我的问题,因为它不能用于自动化。
如果您可以加载 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 包时与事件循环的交互)需要更多的复杂性...