2

I try to find the path to executable of the current active window in python. I am not familiar with system variables and did not know what i should do and i found a few solutions and practicing with them .

First i try to get current active window and finding the related PID and then the path.

import psutil
import win32process
import win32gui

window = win32gui.GetForegroundWindow()
pid = win32process.GetWindowThreadProcessId(window)
active_window_path = psutil.Process(pid[1]).exe()


print("Active window: %s" % str(get_active_window()))

While i get PID with win32process it returns a list .Why ? I had to select 1st element of the list to get the correct result . isn't PID should be a integer ? Why it is returning a list ? And why 2nd element is correct and not first ?

user7685914
  • 83
  • 1
  • 9

1 Answers1

4

It's part of [GitHub]: mhammond/pywin32 - Python for Windows (pywin32) Extensions, which is a Python wrapper over WINAPIs.

Change (the relevant parts of) your code (not mandatory, just for readability) to:

import win32process as wproc

# ...

tid, pid = wproc.GetWindowThreadProcessId(window)

active_window_path = psutil.Process(pid).exe()
CristiFati
  • 38,250
  • 9
  • 50
  • 87