Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pexpect send cursor movement

Tags:

python

pexpect

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()
like image 771
Marwan Alsabbagh Avatar asked Nov 26 '25 15:11

Marwan Alsabbagh


2 Answers

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)
like image 185
Marwan Alsabbagh Avatar answered Nov 29 '25 04:11

Marwan Alsabbagh


How about using escape sequence for up(^[[A) or down(^[[B) like this.

child.send("\033[A")  # up
child.send("\033[B")  # down
like image 44
Tsuneo Yoshioka Avatar answered Nov 29 '25 04:11

Tsuneo Yoshioka



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!