获取前台窗口的进程ID
我正在尝试在Python中构建时间跟踪器,以记录我正在使用的应用程序的屏幕时间。 我用来使前景窗口的PID的方法大部分时间都很好:
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)
但是有时 getwindowthreadProcessid (第7行)返回一个奇怪的pid,有时为负:
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)
...而在我的情况下,在我的系统上约为18000。
它发生随机发生,主要是在使用Chrome时,如果我关闭并重新打开窗口,则PID再次正常,并且我可以正常获得该过程名称。
有人知道为什么会发生或推荐另一种方法吗?
我尝试重新安装库。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
找到了问题。
有时
getForegroundWindow
认为前景窗口是系统空闲过程,然后getWindowThreadProcessID
返回与该过程相对应的PID的列表 - [0(始终有效),{一些大的数量}(始终无效)],而其他过程的第一个PID始终无效(这就是为什么要获得正确的PID,我使用pid [-1]
)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]
)