01 | Python语言: windows平台下如何用Python杀进程 |
02 | #from : http://www.joyloft.net/?p=1031 |
03 | # "这段代码来自于一个很简单的场景: |
04 | # 在python中调一个程序。给这个程序设置一个timeout |
05 | # 假如一段时间程序还没有返回,就杀掉这个这个新开的进程。 |
06 | # 本来以为我肯定不是第一个遇到这个问题的人, |
07 | # 但是网上搜了好久都没找到完整的办法,自己搞了一个。" |
08 | |
09 | import ctypes |
10 | import sys |
11 | |
12 | TH32CS_SNAPPROCESS = 0x00000002 |
13 | class PROCESSENTRY32(ctypes.Structure): |
14 | _fields_ = [( "dwSize" , ctypes.c_ulong), |
15 | ( "cntUsage" , ctypes.c_ulong), |
16 | ( "th32ProcessID" , ctypes.c_ulong), |
17 | ( "th32DefaultHeapID" , ctypes.c_ulong), |
18 | ( "th32ModuleID" , ctypes.c_ulong), |
19 | ( "cntThreads" , ctypes.c_ulong), |
20 | ( "th32ParentProcessID" , ctypes.c_ulong), |
21 | ( "pcPriClassBase" , ctypes.c_ulong), |
22 | ( "dwFlags" , ctypes.c_ulong), |
23 | ( "szExeFile" , ctypes.c_char * 260 )] |
24 | |
25 | def getProcList(): |
26 | CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot |
27 | Process32First = ctypes.windll.kernel32.Process32First |
28 | Process32Next = ctypes.windll.kernel32.Process32Next |
29 | CloseHandle = ctypes.windll.kernel32.CloseHandle |
30 | hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0 ) |
31 | pe32 = PROCESSENTRY32() |
32 | pe32.dwSize = ctypes.sizeof(PROCESSENTRY32) |
33 | if Process32First(hProcessSnap,ctypes.byref(pe32)) = = False : |
34 | print >> sys.stderr, "Failed getting first process." |
35 | return |
36 | while True : |
37 | yield pe32 |
38 | if Process32Next(hProcessSnap,ctypes.byref(pe32)) = = False : |
39 | break |
40 | CloseHandle(hProcessSnap) |
41 | |
42 | def getChildPid(pid): |
43 | procList = getProcList() |
44 | for proc in procList: |
45 | if proc.th32ParentProcessID = = pid: |
46 | yield proc.th32ProcessID |
47 | |
48 | def killPid(pid): |
49 | childList = getChildPid(pid) |
50 | for childPid in childList: |
51 | killPid(childPid) |
52 | handle = ctypes.windll.kernel32.OpenProcess( 1 , False , pid) |
53 | ctypes.windll.kernel32.TerminateProcess(handle, 0 ) |
54 | |
55 | |
56 | if __name__ = = '__main__' : |
57 | args = sys.argv |
58 | if len (args) > 1 : |
59 | pid = int (args[ 1 ]) |
60 | killPid(pid) |
61 | else : |
62 | procList = getProcList() |
63 | for proc in procList: |
64 | print proc.szExeFile + ' ' + str (proc.th32ParentProcessID) + ' ' + str (proc.th32ProcessID) |
65 | |
66 | |
67 | #---------------------- |
68 | # |
69 | # Usage demo |
70 | # |
71 | #---------------------- |
72 | import subprocess |
73 | import time |
74 | |
75 | #import winproc |
76 | |
77 | timeout = 2 |
78 | process = subprocess.Popen( "cmd /k ping localhost -t" ,shell = True ) |
79 | start = int (time.time()) |
80 | while process.poll() = = None : |
81 | now = int (time.time()) |
82 | if int (now - start) >timeout: |
83 | pid = process.pid |
84 | break |
85 | |
86 | winproc.killPid(pid) |
87 | |
88 | print "End" |
联系客服