在mac终端中 - 如何从stdin获得箭头键击?

时间:2014-07-09 07:56:18

标签: python macos terminal stdin

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

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

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

另外,'阅读'在mac术语中,不支持小于1秒的超时。

什么吗?

谢谢,

2 个答案:

答案 0 :(得分:0)

我不确定你在找什么 -

  1. 模拟按键到应用程序的方法,或
  2. 生成简单对话框的方法,或
  3. 从键盘读取字符的方法......
  4. 但是,这些可能会给你一些想法:

    For 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
    

    For 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
    

答案 1 :(得分:0)

根据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