python用windowsAPI查找进程
时间: 2023-07-17 21:07:57 浏览: 276
要在Python中使用Windows API查找进程,你可以使用`ctypes`模块来调用相关函数。以下是一个示例代码,可以通过进程名查找进程:
```python
import ctypes
from ctypes import wintypes
# 定义常量
PROCESS_QUERY_INFORMATION = 0x0400
PROCESS_VM_READ = 0x0010
# 定义结构体
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [
("dwSize", wintypes.DWORD),
("cntUsage", wintypes.DWORD),
("th32ProcessID", wintypes.DWORD),
("th32DefaultHeapID", ctypes.POINTER(wintypes.ULONG_PTR)),
("th32ModuleID", wintypes.DWORD),
("cntThreads", wintypes.DWORD),
("th32ParentProcessID", wintypes.DWORD),
("pcPriClassBase", wintypes.LONG),
("dwFlags", wintypes.DWORD),
("szExeFile", ctypes.c_char * 260)
]
# 调用CreateToolhelp32Snapshot函数
CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot
CreateToolhelp32Snapshot.argtypes = [wintypes.DWORD, wintypes.DWORD]
CreateToolhelp32Snapshot.restype = wintypes.HANDLE
# 调用Process32First和Process32Next函数
Process32First = ctypes.windll.kernel32.Process32First
Process32First.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
Process32First.restype = wintypes.BOOL
Process32Next = ctypes.windll.kernel32.Process32Next
Process32Next.argtypes = [wintypes.HANDLE, ctypes.POINTER(PROCESSENTRY32)]
Process32Next.restype = wintypes.BOOL
def find_process_by_name(process_name):
# 创建进程快照
snapshot = CreateToolhelp32Snapshot(0x2, 0)
# 初始化PROCESSENTRY32结构体
pe32 = PROCESSENTRY32()
pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
# 遍历进程列表
if Process32First(snapshot, ctypes.byref(pe32)):
while True:
# 判断进程名是否匹配
if process_name.lower() == pe32.szExeFile.decode('utf-8').lower():
process_id = pe32.th32ProcessID
print("进程名: {}, 进程ID: {}".format(pe32.szExeFile.decode('utf-8'), process_id))
# 获取下一个进程信息
if not Process32Next(snapshot, ctypes.byref(pe32)):
break
# 关闭进程快照句柄
ctypes.windll.kernel32.CloseHandle(snapshot)
# 测试示例
process_name = "notepad.exe"
find_process_by_name(process_name)
```
在上面的示例中,我们定义了`PROCESSENTRY32`结构体来存储进程信息。然后使用`CreateToolhelp32Snapshot`函数创建进程快照,并使用`Process32First`和`Process32Next`函数遍历进程列表。在遍历过程中,我们判断进程名是否匹配,并输出对应的进程名和进程ID。
你可以将`process_name`变量设置为你要查找的进程名,然后运行示例代码来查找进程。请注意,为了使用Windows API,你需要在Windows操作系统上运行此代码。
阅读全文