[python-win32] Expect-like behavior

Tim Golden mail at timgolden.me.uk
Fri Sep 14 10:34:25 CEST 2007


Tennis Smith wrote:
> I'm new to both python and consequently its use on win32.  I understand
> from lots of sources that "pexpect" is the overall best Expect-like
> implementation in python. *But* I also see that the only way to make it
> work in win32 is on cygwin.   Unfortunately, that isn't an option for my
> users.  We use the ActiveState python and would like to have Expect
> functionality on that rather than installing/supporting 2 different
> python implementations on the same machine.

> Mostly what's needed is the ability to spawn processes (with a timeout)
> and parse their output.

I *assume* you're the same person who's already posted under
the alias "gamename" with a question which seems identical
in its essentials? If you're not then I apologise and chalk
one up to the gods of coincidence. If you are, then I would
suggest that it appears slightly rude to sidestep such advice
as is already coming your way and to post again as though
no-one's tried to help you so far.

(Not sure where you are in the world, but I'm in the UK and
I'm just returning to the online world after a few hours of
sleep and other essentials)

 From your description above and the details of the problem
yesterday, it looks to me as though an expect solution might
well be overkill. The subprocess module, part of the stdlib
from Python 2.4 onwards and available as an extension module
before that, offers ways to kick off processes, read their
output, and check for completion. I thought it also exposed
some kind of .terminate method, but it doesn't look like it.
Instead you can use win32api.TerminateProcess from the
pywin32 extensions, passing in the (non-public) ._handle
attribute of the subprocess Popen object.

Noddy example which fires up a notepad instance and
waits up to 10 seconds for you to close it. If you
don't, it is forcibly terminated.

<code>
import time
import subprocess
import win32api

notepad = subprocess.Popen (["notepad.exe"])
t0 = time.time ()
while time.time () < t0 + 10:
   if notepad.poll () == 0:
     print "Finished"
     break
else:
   print "Terminating..."
   win32api.TerminateProcess (notepad._handle, 0)

</code>

TJG


More information about the python-win32 mailing list