ActiveState Code

Recipe 347462: Terminating a subprocess on Windows


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.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# 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.

Comments

  1. 1. At 4 p.m. on 28 apr 2005, stewart midwinter said:

    Only on Python > 2.2. 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/

  2. 2. At 11:22 p.m. on 15 nov 2005, Claveau Michel said:

    You can add this method. # Kill the process with windows TASKKILL utility

    import os

    os.popen('TASKKILL /PID '+str(process.pid)+' /F')

  3. 3. At 11:25 p.m. on 15 nov 2005, Claveau Michel said:

    You can add this method. # Kill the process with windows TASKKILL utility

    import os

    os.popen('TASKKILL /PID '+str(process.pid)+' /F')

Sign in to comment