Relax ZeroC
Relax ZeroC

Reputation: 683

How can I get process name using Python

I know I can get processId by GetWindowThreadProcessId(hwnd) like ,

pid = win32process.GetWindowThreadProcessId(hwnd)

but , how can I use pid to get process name (ex: chrome.exe,explorer.exe...etc)

Thanks

Upvotes: 1

Views: 8234

Answers (2)

Andy
Andy

Reputation: 50630

If you are willing to use a 3rd party module, you can do this easily with psutil

First you need to install it:

pip install psutil

Then, assuming you have a process ID aready, you just need to do this:

import psutil
PID = 5220
print(psutil.Process(PID).name())

In my case, this prints:

python.exe

Upvotes: 4

fedepad
fedepad

Reputation: 4609

You're using the win32 modules so you could do:

import win32api
import win32process
import win32con

.....

pid = win32process.GetWindowThreadProcessId(hwnd)
handle = win32api.OpenProcess(win32con.PROCESS_QUERY_INFORMATION | win32con.PROCESS_VM_READ, False, pid[1])
proc_name = win32process.GetModuleFileNameEx(handle, 0)

By the way, it's done in the following:
http://nullege.com/codes/show/src%40f%40p%40fpdb-sql-HEAD%40pyfpdb%40WinTables.py/135/win32process.GetWindowThreadProcessId/python
For a cross platform solution I would probably try to use psutil as mentioned by others already. You can also look the following:
https://www.blog.pythonlibrary.org/2010/10/03/how-to-find-and-list-all-running-processes-with-python/

Upvotes: 4

Related Questions