在pexp中创建交互式选项

2024-04-26 03:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个有点笨拙的问题,因为我想不出一个好的方式来描述它,但是在expect中,您可以这样做:

interact {
    \001 {do_something}
    \003 {do_something_else}
    "?" {
      set timeout 1
      expect_user {
                   "?" {send "?"}
                   timeout {send_user "show a menu of the things you can do"}
      }
      stty raw -echo
      set timeout 60
    }
    \035 {send "^]"
      send "quit\r"
      send_user "\n"
      exit
    }
  }

这将创建一个交互式会话,用户可以像往常一样进行业务,但是按下键盘组合键(ctrl+actrl+cctrl+e?等)执行操作或显示描述可能的快捷方式的文本。在

我正在尝试将许多脚本更新到python&pexpect,但无法确定这在pexpect中是否可行。我试着用一个输入过滤器,但似乎这并不是一个合适的地方,或者我似乎找不到任何有用的例子。在

@pynexj:试过你的脚本,不过我没有从ctrl命令中得到任何关于stdout的信息。在

^{pr2}$

Tags: 脚本sendshow方式timeoutdoelsesomething
1条回答
网友
1楼 · 发布于 2024-04-26 03:04:03

请参见以下示例(适用于Python2Python3):

[STEP 114] # cat foo.py
import pexpect

def input_filter(s):
    if s == b'\x03':
        return b'\r: r u going to kill me? press ctrl-d to exit!\r'
    elif s == b'\x04':
        return b'\r: ok, bye; exit\r'
    else:
        return s

proc = pexpect.spawn('bash  norc')
proc.interact(input_filter=input_filter)
proc.expect(pexpect.EOF)
[STEP 115] # python foo.py
bash-4.4# ps                      <  user input
   PID TTY          TIME CMD
 77616 pts/56   00:00:00 bash
 77617 pts/56   00:00:00 ps
bash-4.4#                         <  press CTRL-C
bash-4.4# : r u going to kill me? press ctrl-d to exit!
bash-4.4#                         <  press CTRL-D
bash-4.4# : ok, bye; exit
exit
[STEP 116] #

相关问题 更多 >

    热门问题