python pexpect sendcontrol key characters

SSSSSam picture SSSSSam · Jul 2, 2012 · Viewed 20.8k times · Source

I am working with pythons pexpect module to automate tasks, I need help in figuring out key characters to use with sendcontrol. how could one send the controlkey ENTER ? and for future reference how can we find the key characters?

here is the code i am working on.

#!/usr/bin/env python

import pexpect

id = pexpect.spawn ('ftp 192.168.3.140')

id.expect_exact('Name')

id.sendline ('anonymous')

id.expect_exact ('Password')
*# Not sure how to send the enter control key
id.sendcontrol ('???')* 

id.expect_exact ('ftp')

id.sendline ('dir')

id.expect_exact ('ftp')

lines = id.before.split ('\n')

for line in lines :
        print line

Answer

ottomeister picture ottomeister · Jul 2, 2012

pexpect has no sendcontrol() method. In your example you appear to be trying to send an empty line. To do that, use:

    id.sendline('')

If you need to send real control characters then you can send() a string that contains the appropriate character value. For instance, to send a control-C you would:

    id.send('\003')

or:

    id.send(chr(3))

Responses to comment #2:

Sorry, I typo'ed the module name -- now fixed. More importantly, I was looking at old documentation on noah.org instead of the latest documentation at SourceForge. The newer documentation does show a sendcontrol() method. It takes an argument that is either a letter (for instance, sendcontrol('c') sends a control-C) or one of a variety of punctuation characters representing the control characters that don't correspond to letters. But really sendcontrol() is just a convenient wrapper around the send() method, which is what sendcontrol() calls after after it has calculated the actual value that you want to send. You can read the source for yourself at line 973 of this file.

I don't understand why id.sendline('') does not work, especially given that it apparently works for sending the user name to the spawned ftp program. If you want to try using sendcontrol() instead then that would be either:

    id.sendcontrol('j')

to send a Linefeed character (which is control-j, or decimal 10) or:

    id.sendcontrol('m')

to send a Carriage Return (which is control-m, or decimal 13).

If those don't work then please explain exactly what does happen, and how that differs from what you wanted or expected to happen.