【问题标题】:tcl pause & waiting for key pressed to continuetcl 暂停 & 等待按键继续
【发布时间】:2013-09-30 08:22:10
【问题描述】:

我正在 tcl 中寻找一种方法来暂停脚本(例如在一些带有“puts”的输出之后)并等待用户按下一个键,然后再继续输出剩余的文本。

【问题讨论】:

  • 您确定要将其构建到脚本中吗?有人可能想将输出发送到文件或通过管道将其发送到grepsed 或其他任何地方。更好的解决方案是将脚本输出通过管道传输到程序之一 more(也适用于 Windows)或 less

标签: key tcl pressed


【解决方案1】:

Windows 的潜在解决方案:

exec -ignorestderr [file join $env(windir) system32 cmd.exe] /c pause

这也会注意到非 ascii 按键(例如箭头键、Escape 等)。

另一个解决方案是Raw Mode on Windows 提出的 多纳尔研究员above (感谢链接!),可以概括为 这两行代码:

twapi::modify_console_input_mode stdin -lineinput 0 -echoinput 0
read stdin 1

这并没有注意到Escape、箭头键之类的(你可能需要稍后恢复控制台输入模式)。

【讨论】:

    【解决方案2】:

    感谢 Hai Vu 的回答,如果您使用的是类似 unix 的系统,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
    

    Tcl wiki 上的详细讨论链接:Reading a single character from the keyboard using Tcl

    【讨论】:

    • 在 Windows 上做同样的事情需要使用 TWAPI 包,以便您可以更改终端模式。这是little long for a comment
    • 额外说明:如果您想多次以这种方式键入一个键,stty -icanon 具有预期的效果,但不像stty raw 那样严重 - 例如它让用户像往常一样使用^C 退出。
    【解决方案3】:

    您只需使用gets 从标准输入读取:

    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
    

    【讨论】:

    • +1 为您的答案。提供了漂亮的代码。看到您的回答后,我想到了 1 个问题。如果我希望用户“按任意键”怎么办?不只是“输入”......这样的事情可能吗?我会将此问题作为一个新线程开始,但对这种情况没有信心..有什么选择/方式吗?
    • 感谢您提供这个短代码,它与回车键配合得很好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-02
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2020-05-07
    相关资源
    最近更新 更多