【发布时间】:2019-07-05 17:54:09
【问题描述】:
我正在运行tclsh some.tcl,它在遇到 eof 后退出。我希望它不要退出并让用户控制交互。 请注意,我们可以通过调用 shell 和源脚本来做到这一点,但这并不能解决我的问题,因为它不能用于自动化。
【问题讨论】:
-
不是重复的。这个问题是关于进入一个命令循环,而不仅仅是等待一个键。
标签: tcl
我正在运行tclsh some.tcl,它在遇到 eof 后退出。我希望它不要退出并让用户控制交互。 请注意,我们可以通过调用 shell 和源脚本来做到这一点,但这并不能解决我的问题,因为它不能用于自动化。
【问题讨论】:
标签: tcl
如果您可以加载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 包时与事件循环的交互)将需要相当多的复杂性...
【讨论】: