I'm trying to build a time tracker in Python, that records the screen time of applications I'm using. Approach that I use to get the PID of foreground window works fine most of the time:
import psutil
import win32gui
import win32process
while True:
try:
time.sleep(0.5)
pid1 = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
process1 = psutil.Process(pid1[-1]).name()
time.sleep(0.5)
pid2 = win32process.GetWindowThreadProcessId(win32gui.GetForegroundWindow())
process2 = psutil.Process(pid2[-1]).name()
if process1 != process2:
print(process2)
except ValueError or psutil.NoSuchProcess or ProcessLookupError as error:
print(error)
But sometimes GetWindowThreadProcessId (line 7) returns a weird PID, sometimes negative:
pid must be a positive integer (got -571069920)
pid must be a positive integer (got -571069920)
pid must be a positive integer (got -571069920)
pid must be a positive integer (got -571069920)
pid must be a positive integer (got -571069920)
...while in my case the largest PID on my system was around 18000.
It happens randomly, mostly when using Chrome, if I close and reopen the window, it's PID is normal again, and I can get it's process name normally.
Does someone know why it is happening or recommend an alternative approach?
I tried reinstalling the libraries.
Found the problem.
Sometimes
GetForegroundWindow
thinks that the foreground window is System Idle Process, thenGetWindowThreadProcessId
returns a list of to PIDs corresponding to that process - [0 (always valid), {some big number} (always invalid)], while the other processes have the first PID always invalid (this is why to get the correct PID I usepid[-1]
)