python能否通过句柄得到外部程序的路径?
c++通过函数
GetWindowThreadProcessId CreateToolhelp32Snapshot 可以查到exe程序的路径,python如何查到?
回答:
def _win32_check_running_pid(self, pid):
class PROCESSENTRY32(ctypes.Structure): _fields_ = [("dwSize", ctypes.c_ulong),
("cntUsage", ctypes.c_ulong),
("th32ProcessID", ctypes.c_ulong),
("th32DefaultHeapID", ctypes.c_ulong),
("th32ModuleID", ctypes.c_ulong),
("cntThreads", ctypes.c_ulong),
("th32ParentProcessID", ctypes.c_ulong),
("pcPriClassBase", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("szExeFile", ctypes.c_char * 260)]# win64,这行代码如何改?
CreateToolhelp32Snapshot = ctypes.windll.kernel32.CreateToolhelp32Snapshot
Process32First = ctypes.windll.kernel32.Process32First
Process32Next = ctypes.windll.kernel32.Process32Next
CloseHandle = ctypes.windll.kernel32.CloseHandle
TH32CS_SNAPPROCESS = 0x00000002 # win32 magic number
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0)
pe32 = PROCESSENTRY32()
pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
result = False
if not Process32First(hProcessSnap, ctypes.byref(pe32)):
_log.debug("Failed getting first process.")
CloseHandle(hProcessSnap)
return result
while True:
if pe32.th32ProcessID == pid:
result = True
break
if not Process32Next(hProcessSnap, ctypes.byref(pe32)):
break
CloseHandle(hProcessSnap)
return result
网上找到一段代码,返回是bytes,转换总是乱码,怀疑是32位程序转换在win64出错
回答:
#遍历process获取程序名def win32_get_path(pid):
class PROCESSENTRY32(ctypes.Structure):
_fields_ = [("dwSize", ctypes.c_ulong),
("cntUsage", ctypes.c_ulong),
("th32ProcessID", ctypes.c_ulong),
("th32DefaultHeapID", ctypes.c_void_p),
("th32ModuleID", ctypes.c_ulong),
("cntThreads", ctypes.c_ulong),
("th32ParentProcessID", ctypes.c_ulong),
("pcPriClassBase", ctypes.c_ulong),
("dwFlags", ctypes.c_ulong),
("szExeFile", ctypes.c_char * 260)]
kernel32 = ctypes.windll.kernel32
hProcessSnap = kernel32.CreateToolhelp32Snapshot(0x00000002, 0)
pe32 = PROCESSENTRY32()
pe32.dwSize = ctypes.sizeof(PROCESSENTRY32)
ret = kernel32.Process32First(hProcessSnap, ctypes.byref(pe32))
while ret:
if pe32.th32ProcessID == pid:
kernel32.CloseHandle(hProcessSnap)
#如果要获取全路径 还要遍历module
return pe32.szExeFile.decode("gbk")
ret = kernel32.Process32Next(hProcessSnap, ctypes.byref(pe32))
kernel32.CloseHandle(hProcessSnap)
ERROR_NO_MORE_FILES = 18
err = kernel32.GetLastError()
if err is not ERROR_NO_MORE_FILES:
print("error %d" % err)
return None
#通过psapi获取全路径
def win32_get_path2(pid):
def invalid_handle(handle):
return handle == 0 or handle == -1
kernel32 = ctypes.windll.kernel32
psapi = ctypes.windll.psapi
h_Process = kernel32.OpenProcess(0x0400, 0, pid)
if invalid_handle(h_Process):
print("error %d" % kernel32.GetLastError())
return None
path = (ctypes.c_char * 260)()
psapi.GetModuleFileNameExA(h_Process, 0, path, 260)
kernel32.CloseHandle(h_Process)
return path.value.decode("gbk")
以上是 python能否通过句柄得到外部程序的路径? 的全部内容, 来源链接: utcz.com/a/157857.html