0

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.

0

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

1

You can use psutil, it's more simpler and pythonic: psutil.Process().name() , and it will work on both Windows and POSIX.

1 Comment

thanks,I know I can use psutil , but can I use win32 api directly ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.