I'm looking for a way in tcl to pause the script (for example after some outputs with "puts") and wait for a key pressed from the user before continuing to output the remaining text.
With gratitude to Hai Vu's answer, if you're on a unix-like system with stty
proc anykey {{msg "Hit any key: "}} {
set stty_settings [exec stty -g]
exec stty raw -echo
puts -nonewline $msg
flush stdout
read stdin 1
exec stty $stty_settings
puts ""
}
puts 1
anykey
puts 2
Link to thorough discussion on Tcl wiki: Reading a single character from the keyboard using Tcl
You just use gets
to read from stdin:
proc pause {{message "Hit Enter to continue ==> "}} {
puts -nonewline $message
flush stdout
gets stdin
}
pause "Hurry, hit enter: "; # Sample usage 1
pause; # Sample usage 2, use default message
A potential solution for Windows:
exec -ignorestderr [file join $env(windir) system32 cmd.exe] /c pause
This notices non-ascii keypresses, too (such as arrow keys, Escape etc.).
Another solution is the Raw Mode on Windows proposed by Donal Fellows above (thanks for the link!), which can be summarized into these two lines of code:
twapi::modify_console_input_mode stdin -lineinput 0 -echoinput 0
read stdin 1
This does not notice Escape, arrows keys and the like (and you may need to restore the console input mode later).
来源:https://stackoverflow.com/questions/18993122/tcl-pause-waiting-for-key-pressed-to-continue