Python 在用户不活动时执行函数

Python 在用户不活动时执行函数,python,automation,user-inactivity,Python,Automation,User Inactivity,在工作中,我们必须做自己的时间管理和控制不时。因为我总是忘记,当我休息的时候以及休息的时间,我决定写一个python脚本,在启动时运行,在我5分钟没有移动鼠标或在键盘上键入内容后写入当前时间 import datetime def writetime(): t = datetime.datetime.now() with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'a') as f: f.write('%s \

在工作中,我们必须做自己的时间管理和控制不时。因为我总是忘记,当我休息的时候以及休息的时间,我决定写一个python脚本,在启动时运行,在我5分钟没有移动鼠标或在键盘上键入内容后写入当前时间

import datetime


def writetime():
    t = datetime.datetime.now()

    with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'a') as f:
        f.write('%s \n' % t)

我只是不知道如何在上次输入后经过一定时间后执行函数writetime。

pynput
看起来可能适合您

大概是

from pynput import mouse
with mouse.Listener(on_click=reset_timer,
    on_move=reset_timer, 
    on_scroll=reset_timer) as listener:
    begin_timer()

另一种方法可能是在5分钟后关闭显示器屏幕(屏幕保护程序选项),然后编写一个脚本来检测显示器状态

下面是一个如何执行此操作的示例:


快乐编码

这可能不是最干净的解决方案,但因为我是一名Python新手,所以我对它非常满意。 导入日期时间 从ctypes导入结构、Windell、c_uint、sizeof、byref 导入时间

class LASTINPUTINFO(Structure):
    _fields_ = [
        ('cbSize', c_uint),
        ('dwTime', c_uint),
    ]


def get_idle_duration():
    lastInputInfo = LASTINPUTINFO()
    lastInputInfo.cbSize = sizeof(lastInputInfo)
    windll.user32.GetLastInputInfo(byref(lastInputInfo))
    millis = windll.kernel32.GetTickCount() - lastInputInfo.dwTime
    return millis / 1000.0


while 1:
    GetLastInputInfo = int(get_idle_duration())

    if GetLastInputInfo >= 10:
        start = time.time()
        startTime = datetime.datetime.now()

        while GetLastInputInfo >= 10:
            GetLastInputInfo = int(get_idle_duration())
            if GetLastInputInfo < 10:
                end = time.time()
                time_elapsed = end - start + 10
                if time_elapsed >= 10:
                    with open("C:\\Users\\[USER]\\Desktop\\time.txt", 'w') as f:
                        f.write('Pause from ' + str(startTime) + ' to ' + str(
                            datetime.datetime.now()) + '\nDuration: ' + str(time_elapsed))
类LASTINPUTINFO(结构):
_字段=[
('cbSize',c_uint),
('dwTime',c_uint),
]
def get_idle_duration():
lastInputInfo=lastInputInfo()
lastInputInfo.cbSize=sizeof(lastInputInfo)
user32.GetLastInputInfo(byref(lastInputInfo))
millis=windell.kernel32.GetTickCount()-lastInputInfo.dwTime
返回毫秒/1000.0
而1:
GetLastInputInfo=int(get\u idle\u duration())
如果GetLastInputInfo>=10:
开始=时间。时间()
startTime=datetime.datetime.now()
当GetLastInputInfo>=10时:
GetLastInputInfo=int(get\u idle\u duration())
如果GetLastInputInfo<10:
end=time.time()
经过的时间=结束-开始+10
如果经过的时间>=10:
打开(“C:\\Users\\[USER]\\Desktop\\time.txt,'w')作为f:
f、 写入('从'+str(开始时间)+'暂停到'+str(
datetime.datetime.now())+'\n持续时间:'+str(经过的时间))
出于测试目的,我将标记为缺席的时间设置为10秒。因此,如果你想做一些类似的事情,只需确保将所有10的时间都更改为希望的时间(以秒为单位)