Welcome, guest | Sign In | My Account | Store | Cart

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, 29 lines
 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)

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.

3 comments

stewart midwinter 19 years ago  # | flag

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/

Claveau Michel 18 years, 5 months ago  # | flag

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

import os

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

Claveau Michel 18 years, 5 months ago  # | flag

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

import os

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