How to use pty.py?

Michael Hudson mwh at python.net
Tue Dec 11 10:02:36 EST 2001


iwk <iwk_nospam at xs4all_nospam.nl> writes:

> I need to pass input to a program at a customers' site which bypasses
> stin/out and reads/writes to/from a terminal, just like ssh when it
> asks for a password. So I cannot pipe the data to the program. To the
> best of my knowledge I should be able to use pty.py to start the
> program and provide it with the required input. But how? Does anyone
> have some examples?

Oh, something like this:

/>> def su():
|..  import os, time
|..  def p(d=0.2): time.sleep(d)
|..  pid, fd = os.forkpty()
|..  if pid == 0:
|..   os.execlp("su","su")
|..  else:
|..   p()
|..   print `os.read(fd, 1000)`
|..   p()
|..   os.write(fd, "XXXX\r")
|..   p(2)
|..   print `os.read(fd, 1000)`
\__
->> su()
'Password: '
'\r\nsu: incorrect password\r\n'
->> 

It all gets a bit messy, because you have to let any write()s the
child does finish by sucking stuff out of `fd' before *you* can write
any data to it (otherwise the child will be blocked in its call to
write() and will never call read()).  This means you need to know
pretty exactly how the child behaves, and perhaps can begin to
understand why expect is called what it is.

There are probably wrappers that make it all a bit less painful -- and
maybe a touch more portable -- but I've never used them.

Cheers,
M.

-- 
  And then the character-only displays went away (leading to
  increasingly silly graphical effects and finally to ads on
  web pages).                      -- John W. Baxter, comp.lang.python



More information about the Python-list mailing list