本帖最后由 苏紫方璇 于 2024-12-1 13:20 编辑
[Python] 纯文本查看 复制代码 ###还有一些问题 待修改
import csv
from datetime import datetime
from pynput import mouse
from pygetwindow import getActiveWindow
from pynput import mouse
# def on_click(x, y, button, pressed):
# if pressed:
# # 获取当前活动窗口
# active_window = getActiveWindow()
# if active_window:
# print(f"Mouse clicked. Active window: {active_window.title}")
# 初始化计数器
total_clicks = 0
left_clicks = 0
right_clicks = 0
# 定义文件路径和CSV文件头
csv_file_path = 'mouse_clicks_1127.csv'
csv_headers = ['Click Type', 'X Coordinate', 'Y Coordinate', 'click_data', 'click_time', 'Total Clicks', 'Left Clicks', 'Right Clicks', 'Window']
# 创建一个函数来写入CSV文件(仅在程序开始时写入表头)
def write_csv_header(file_path, headers):
with open(file_path, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(headers)
# 定义一个函数来处理鼠标点击事件并写入CSV文件
def on_click(x, y, button, pressed):
global total_clicks, left_clicks, right_clicks
if pressed:
click_data = datetime.now().strftime('%Y-%m-%d')
click_time = datetime.now().strftime('%H:%M:%S')
click_type = 'Left' if button == mouse.Button.left else 'Right'
active_window = getActiveWindow()
print(f"Mouse clicked. Active window: {active_window.title}")
# 更新点击次数
if click_type == 'Left':
left_clicks += 1
elif click_type == 'Right':
right_clicks += 1
total_clicks += 1
# 准备要写入CSV的数据行
row_data = [click_type, x, 1080-y, click_data, click_time, total_clicks, left_clicks, right_clicks, active_window.title]
# 写入CSV文件
with open(csv_file_path, mode='a', newline='') as file:
writer = csv.writer(file)
writer.writerow(row_data)
# 打印点击信息到控制台(可选)
print(f'{click_type} click at ({x}, {y}) at {click_data} {click_time} (Total clicks: {total_clicks}, Left clicks: {left_clicks}, Right clicks: {right_clicks})')
# 在程序开始时写入CSV表头(如果文件不存在或为空)
try:
# 尝试打开文件以检查其是否为空
with open(csv_file_path, 'r') as file:
# 如果文件不为空,则不需要写入表头
first_line = file.readline().strip()
if first_line:
# 文件不为空,表头已存在
pass
else:
# 文件为空,写入表头
write_csv_header(csv_file_path, csv_headers)
except FileNotFoundError:
# 文件不存在,写入表头
write_csv_header(csv_file_path, csv_headers)
# 创建一个监听器,绑定鼠标点击事件处理函数
with mouse.Listener(on_click=on_click) as listener:
print("Start listening for mouse clicks. Press Ctrl+C to stop and save the data to a CSV file.")
listener.join() # 这行代码会使程序一直运行,直到你手动停止它(例如,通过 Ctrl+C) |