问题
How can you send cursor movements like the up,down,left,right keys with pexpect. The example below is to automate elinks which uses the up/down keys to select different links on a page.
from pexpect import spawn
child = spawn('elinks http://python.org')
#what goes here to send down key
child.interact()
回答1:
How about using escape sequence for up(^[[A) or down(^[[B) like this.
child.send("\033[A") # up
child.send("\033[B") # down
回答2:
The below script has the codes for all the four cursor movements, with an example of how one might use it in pexpect. To discover the exact string sequences for any typed in text you may use the get_keys.py script below.
KEY_UP = '\x1b[A'
KEY_DOWN = '\x1b[B'
KEY_RIGHT = '\x1b[C'
KEY_LEFT = '\x1b[D'
child.sendline(KEY_DOWN * 5) #send five key downs
get_keys.py
import curses
screen = curses.initscr()
screen.addstr("Press any set of keys then press enter\n")
keys = ''
while True:
event = screen.getkey()
if event == "\n":
break
keys += event
curses.endwin()
print repr(keys)
来源:https://stackoverflow.com/questions/12981982/pexpect-send-cursor-movement