[Python 2.4/2.5] subprocess module is sorely deficient?

Harishankar v.harishankar at gmail.com
Tue Apr 22 09:17:43 EDT 2008


On Tuesday 22 Apr 2008 18:00:02 Nick Craig-Wood wrote:
> There is a recipe in the cookbook
>
>   http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554
>
> Which I've used and it works.
Thanks. I found that recipe too. I was hoping I could cook up something 
similar without having to use the module win32api, but looks like that's not 
the case.

>
> you can also (if on unix) use
>
>   http://www.noah.org/wiki/Pexpect
>
I'm on Linux. Debian. Pexpect would do the job fine too. The only thing is 
it's a third party module and so would reduce the portability of my 
application. But never mind. I guess I have to make a compromise one way or 
the other.

> import os
> from subprocess import *
> from subprocess import mswindows
> from time import sleep
>
> if mswindows:
>     import win32api
> else:
>     import signal
>
> class PopenNB(Popen):
>     # - see cookbook recipe for rest of stuff
>     # ...
>     def kill(self, killpg=False):
>         """
>         Kill the running process
>         """
>         pid = self.pid
>         if mswindows:
>             # Kill the process using win32api and pid - ignore errors
>             try:
>                 PROCESS_TERMINATE = 1
>                 handle = win32api.OpenProcess(PROCESS_TERMINATE, False,
> pid) win32api.TerminateProcess(handle, -1)
>                 win32api.CloseHandle(handle)
>             except pywintypes.error:
>                 pass
>         else:
>             # Kill the process by sending the pid / process group a
> 	    signal
>             if killpg:
>                 try:
>                     pgid = os.getpgid(pid)
>                 except OSError:
>                     killpg = False
>             try:
>                 if killpg:
>                     os.killpg(pgid, signal.SIGTERM)
>                 else:
>                     os.kill(pid, signal.SIGTERM)
>             except OSError:
>                 return
>             sleep(1.0)
>             try:
>                 if killpg:
>                     os.killpg(pgid, signal.SIGKILL)
>                 else:
>                     os.kill(pid, signal.SIGKILL)
>             except OSError:
>                 return

Thanks for this bit of code. It should probably be adaptible to my needs.

By the way, the win32api seems to be a nonstandard module (i.e. not present in 
the main distribution).

-- 
Regards,
V. Harishankar

http://hari.literaryforums.org
http://harishankar.org



More information about the Python-list mailing list