我怎样才能find一个名称的过程,并使用ctypes杀死?

在Windows上,我想通过'exename.exe'的名字find一个进程,然后杀掉它。

我怎样才能通过ctypes而不是其他的第三方模块?

Solutions Collecting From Web of "我怎样才能find一个名称的过程,并使用ctypes杀死?"

尝试这个:

import sys, os.path, ctypes, ctypes.wintypes Psapi = ctypes.WinDLL('Psapi.dll') EnumProcesses = Psapi.EnumProcesses EnumProcesses.restype = ctypes.wintypes.BOOL GetProcessImageFileName = Psapi.GetProcessImageFileNameA GetProcessImageFileName.restype = ctypes.wintypes.DWORD coreel32 = ctypes.WinDLL('kernel32.dll') OpenProcess = coreel32.OpenProcess OpenProcess.restype = ctypes.wintypes.HANDLE TerminateProcess = coreel32.TerminateProcess TerminateProcess.restype = ctypes.wintypes.BOOL CloseHandle = coreel32.CloseHandle MAX_PATH = 260 PROCESS_TERMINATE = 0x0001 PROCESS_QUERY_INFORMATION = 0x0400 count = 32 while True: ProcessIds = (ctypes.wintypes.DWORD*count)() cb = ctypes.sizeof(ProcessIds) BytesReturned = ctypes.wintypes.DWORD() if EnumProcesses(ctypes.byref(ProcessIds), cb, ctypes.byref(BytesReturned)): if BytesReturned.value<cb: break else: count *= 2 else: sys.exit("Call to EnumProcesses failed") for index in range(BytesReturned.value / ctypes.sizeof(ctypes.wintypes.DWORD)): ProcessId = ProcessIds[index] hProcess = OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION, False, ProcessId) if hProcess: ImageFileName = (ctypes.c_char*MAX_PATH)() if GetProcessImageFileName(hProcess, ImageFileName, MAX_PATH)>0: filename = os.path.basename(ImageFileName.value) if filename == 'notepad.exe': TerminateProcess(hProcess, 1) CloseHandle(hProcess) 

这可能是作弊,但它甚至没有涉及ctypes。

 import subprocess subprocess.call("taskkill /IM exename.exe") 

taskkill是一个Windows命令; 这只是通过Python调用它。