监控孩子用电脑都干了啥?!
作者:互联网
是不是打开电脑就发觉时间过得超级快?
不知道把时间都花在了哪里?
我们来做一个监控电脑上使用软件的时间的脚本吧!
首先我们先安装win32gui库
pip install win32gui
然后先引入win32gui和time两个库
import time
import win32gui
因为要持续监听,写一个死循环,间隔1秒循环一次
while True:
time.sleep(1)
想要知道电脑此刻最上层的窗口是什么,使用win32gui.GetForegroundWindow()获得window桌面系统最上层的窗口,返回窗口句柄(int)
hwnd = win32gui.GetForegroundWindow()
拿到窗口句柄以后我们要建立一个字典,将窗口句柄给存起来,然后根据句柄获取窗口的名称win32gui.GetWindowText(hwnd),再拿到当前的时间,一并记录到字典中
title = win32gui.GetWindowText(hwnd)
list = use_app_data.get(hwd)
if list == None or len(list) <= 0:
list = []
use_app_data[hwd] = list
list.append({'title': title, 'start': time.time(), 'end': 0, 'total': 0})
如果窗口切换了,句柄会变化,所以记录下之前的句柄,与当前的句柄进行对比,如果发生改变,则说明用户切换了窗口,此时记录窗口的使用时间,放入字典,最后做统计。
完整的代码如下:
# 监控电脑使用各个窗口(软件)的时长
import win32gui
import time
use_app_data = {}
currentWindow = 0
# def save_data_excel(data):
# workbook = xlwt.Workbook()
# wookbook
if __name__ == '__main__':
try:
starttime = time.localtime()
print('开始监控')
print(time.strftime("%Y-%m-%d %H:%M:%S", starttime))
while True:
# 获取最上层的窗口
hwd = win32gui.GetForegroundWindow()
# 检查窗口是不是微信
if hwd != currentWindow:
if currentWindow > 0:
data = list[len(list)-1]
if data['end'] == 0:
data['end'] = time.time()
data['total'] = data['end'] - data['start']
currentWindow = hwd
title = win32gui.GetWindowText(hwd)
list = use_app_data.get(hwd)
if list == None or len(list) <= 0:
list = []
use_app_data[hwd] = list
list.append({'title': title, 'start': time.time(), 'end': 0, 'total': 0})
else:
data = list[len(list)-1]
if data['end'] != 0:
list.append({'title': title, 'start': time.time(), 'end': 0, 'total': 0})
else:
data['end'] = time.time()
data['total'] = data['end'] - data['start']
time.sleep(1)
except:
print(use_app_data)
最后加入一个try...except 用来监控Ctrl+C 的时候终端监听程序,然后打印结果。
PS:
下一期将介绍把监控的数据存入到excel表格当中
标签:窗口,监控,孩子,time,电脑,list,win32gui,句柄,data 来源: https://blog.csdn.net/moonjie444/article/details/106582230