【问题标题】:In the mac terminal - how can I get arrow keystrokes from stdin?在 mac 终端中 - 如何从标准输入获取箭头键击?
【发布时间】:2014-07-09 07:56:17
【问题描述】:

我想用箭头键浏览终端对话框菜单(如 bash 'dialog')

我更喜欢 ruby​​ 解决方案,但 bash/python 可以工作。

read -n1 input # is not good enough, cause the arrow keys are not regular chars.

另外,mac 术语中的“读取”不支持小于 1 秒的超时。

有什么事吗?

谢谢,

【问题讨论】:

    标签: python macos terminal stdin


    【解决方案1】:

    我不确定你在寻找什么 -

    1. 一种模拟应用程序按键的方法,或
    2. 一种生成简单对话框的方法,或
    3. 一种从键盘读取字符的方法...

    但是,这些可能会给你一些想法:

    对于 1:您可能需要查看 Automator 和 Applescript

    tell application "System Events" to tell process "Finder"
       click menu item "New Finder Window" of menu 1 of menu bar item "File" of menu bar 1
    end tell
    

    对于 2:您可以查看 Platypus 以生成对话框和脚本包装器 - 可用 here

    For 3:以下可能会做你想做的事情

    #!/bin/bash
    #
    # Read a key in cbreak mode
    stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
    #
    # If ESCAPE, read next part
    if [ $KEY = $'' ]; then
       stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
       stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
       [ $KEY = "A" ] && echo UP
       [ $KEY = 'B' ] && echo DOWN
       [ $KEY = 'C' ] && echo RIGHT
       [ $KEY = 'D' ] && echo LEFT
       exit
    fi
    echo $KEY
    

    我应该解释一下需要输入if [ $KEY 行

    if [ $KEY = $'CONTROL-V ESCAPE' ]
    

    即输入这 5 件事

    $
    single quote
    Control V
    Escape
    single quote
    

    【讨论】:

    • 非常感谢,#3 正是我所需要的。由于第一个“如果”对我不起作用,因此对其进行了一些修改。我检查它是否是“非逃逸”字符。我的答案如下
    【解决方案2】:

    根据 Mark Setchell 的说法,稍作修改:

    #!/bin/bash
    
    # Read a key in cbreak mode
    stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
    
    # Check if it's a single alphanumeric char
    if $(echo $KEY | grep -q -e "[a-zA-Z0-9]"); then
      echo $KEY
      exit
    # Else we assume escape char (doesn't cover all cases)
    else
      stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
      stty cbreak -echo; KEY=$(dd bs=1 count=1 2>/dev/null); stty -cbreak echo
      [ $KEY == 'A' ] && echo UP
      [ $KEY == 'B' ] && echo DOWN
      [ $KEY == 'C' ] && echo RIGHT
      [ $KEY == 'D' ] && echo LEFT
      exit
    fi
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-07
      • 2011-06-27
      • 2020-09-01
      • 2017-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多