Reputation: 683
I want to get process name (ex:notepad.exe) by using win32 api in Python , so the code like ,
hwnd = FindWindow(None,"123.txt - notepad")
threadid ,pid = win32process.GetWindowThreadProcessId(hwnd)
print('pid=' + str(pid))
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, FALSE, pid)
proc_name = win32process.GetModuleFileNameEx(handle, 0)
but the exception occur ,
pywintypes.error: (299, 'GetModuleFileNameEx', 'ReadProcessMemory
or WriteProcessMemory ....exception')
How can I solve this problem?
Thanks.
Upvotes: 0
Views: 7879
Reputation: 10000
This is a bit modified code from pywinauto getting executable path and name of the process using PyWin32 only:
hwnd = FindWindow(None,"123.txt - notepad")
threadid, pid = win32process.GetWindowThreadProcessId(hwnd)
print('pid=' + str(pid))
from win32com.client import GetObject
_wmi = GetObject('winmgmts:')
# collect all the running processes
processes = _wmi.ExecQuery('Select * from win32_process')
for p in processes:
if isinstance(p.ProcessId, int) and p.ProcessId == pid:
print((p.ProcessId, p.ExecutablePath, p.CommandLine, p.Name))
No need to install WMI
or psutil
.
Upvotes: 3
Reputation: 14817
You can use psutil, it's more simpler and pythonic: psutil.Process().name()
, and it will work on both Windows and POSIX.
Upvotes: 1
Reputation: 2297
You can use the wmi
python module or expose the WMIC
command line utility to get the list of active processes.
import wmi
c = wmi.WMI ()
for process in c.Win32_Process ():
print process.ProcessId, process.Name
Upvotes: 1