ASPN ActiveState Programmer Network  
ActiveState, a division of Sophos
/ Home / Perl / PHP / Python / Tcl / XSLT /
/ Safari / My ASPN /
Cookbooks | Documentation | Mailing Lists | Modules | News Feeds | Products | User Groups
Submit Recipe
My Recipes

All Recipes
All Cookbooks


View by Category

Title: Terminating a subprocess on Windows
Submitter: Jimmy Retzlaff (other recipes)
Last Updated: 2004/11/24
Version no: 1.0
Category: System

 

5 stars 3 vote(s)


Description:

The new subprocess module in Python 2.4 (also available for 2.2 and 2.3 at http://effbot.org/downloads/#subprocess) allows access to the handle of any newly created subprocess. You can use this handle to terminate subprocesses using either ctypes or the pywin32 extensions.

Source: Text Source

# Create a process that won't end on its own
import subprocess
process = subprocess.Popen(['python.exe', '-c', 'while 1: pass'])


# Kill the process using pywin32
import win32api
win32api.TerminateProcess(int(process._handle), -1)


# Kill the process using ctypes
import ctypes
ctypes.windll.kernel32.TerminateProcess(int(process._handle), -1)


# Kill the proces using pywin32 and pid
import win32api
PROCESS_TERMINATE = 1
handle = win32api.OpenProcess(PROCESS_TERMINATE, False, process.pid)
win32api.TerminateProcess(handle, -1)
win32api.CloseHandle(handle)


# Kill the proces using ctypes and pid
import ctypes
PROCESS_TERMINATE = 1
handle = ctypes.windll.kernel32.OpenProcess(PROCESS_TERMINATE, False, process.pid)
ctypes.windll.kernel32.TerminateProcess(handle, -1)
ctypes.windll.kernel32.CloseHandle(handle)

Discussion:

You can use either pywin32 or ctypes to call the Windows TerminateProcess API. Just pick one - there is no need for both. If you don't like accessing the undocumented _handle member of the object returned by Popen, then you can achieve the same result using the documented pid member and the Windows OpenProcess API.



Add comment

Number of comments: 3

Only on Python > 2.2, stewart midwinter, 2005/04/28
Note that the ctypes solution is only available to you if you are using Python 2.3 or higher. You can find it here: http://starship.python.net/crew/theller/ctypes/
Add comment

You can add this method, Claveau Michel, 2005/11/15
# Kill the process with windows TASKKILL utility
import os
os.popen('TASKKILL /PID '+str(process.pid)+' /F')

Add comment

You can add this method, Claveau Michel, 2005/11/15
# Kill the process with windows TASKKILL utility
import os
os.popen('TASKKILL /PID '+str(process.pid)+' /F')

Add comment



Highest rated recipes:

1. A simple XML-RPC server

2. Web service accessible ...

3. Treat the Win32 Registry ...

4. Watching a directory ...

5. Union Find data structure

6. Function Decorators by ...

7. MS SQL Server log monitor

8. Table objects with ...

9. wx twisted support using ...

10. More accurate sum




Privacy Policy | Email Opt-out | Feedback | Syndication
© 2006 ActiveState Software Inc. All rights reserved.