Python application to track time lost between windows applications

50 Views Asked by At

I'm the type of person who easily gets lost at work, I have a lot of distractions on YouTube, WhatsApp, etc. So I decide to create an app to track my time. Here is the code.

import time
import pygetwindow as gw
import win32gui
import win32process
import psutil
import requests

def get_active_application(title):
    try:
        hwnd = win32gui.FindWindow(None, title)
        threadid, pid = win32process.GetWindowThreadProcessId(hwnd)
        process = psutil.Process(pid)
        process_name = process.name()
        return process_name
    except Exception as e:
        print(f"Error in get_active_application: {e}")
        return None

def post_data(user, window_title, window_application, elapsed_time):
    if elapsed_time > 5:
        url = "MyServerPath.php"
        json_data = {
            "user": user,
            "window_title": window_title,
            "window_application": window_application,
            "elapsed_time": int(elapsed_time)
        }
        try:
            response = requests.post(url, json=json_data)
            response.raise_for_status()  # Raise an error for bad responses (4xx or 5xx)
            print(f"USER: {user} Time spent in {window_title} ({window_application}): {int(elapsed_time)} seconds")
        except requests.RequestException as e:
            print("POST request failed:", e)

def log_window_focus(user):
    window_logs = {}

    try:
        while True:
            current_window = gw.getActiveWindow()
            if current_window is not None:
                window_title = current_window.title
                window_application = get_active_application(window_title)

                if window_title not in window_logs:
                    window_logs[window_title] = {"time_spent": 0, "application": window_application}

                start_time = time.time()

                while gw.getActiveWindow() is not None and gw.getActiveWindow().title == window_title:
                    time.sleep(1)

                elapsed_time = time.time() - start_time
                window_logs[window_title]["time_spent"] += elapsed_time
                post_data(user, window_title, window_application, elapsed_time)

    except KeyboardInterrupt:
        print("\nPuta Sumario")
        for window, data in window_logs.items():
            print(f"{window} ({data['application']}): {data['time_spent']} seconds")

if __name__ == "__main__":
    user = "usertest"
    log_window_focus(user)

image here

The problem is, if I have been programming in Python, which is the window I'm working in, how come chrome.exe and msedge.exe are appearing at the same time?

I'm doing something wrong, and I don't see it. BTW, sorry for my english!

0

There are 0 best solutions below