QA Engineering/Tool & Automation

pynput을 이용한 매크로 만들기 step1

일해라폴폴 2023. 9. 1. 10:39
반응형

pynput(파이엔풋)이라는 파이썬 라이브러리로 마우스과 키보드 이벤트를 받아 제어 및 모니터링 (레코딩) 후 매크로 처럼 사용 할 수 있다
급하게 사용해야 하는 UI 테스트 시에 유용할 것 같아 우선 콘솔로 수행하는 스크립트를 남겨본다

pynput documents 상세페이지 바로가기
https://pynput.readthedocs.io/en/latest/

 

pynput Package Documentation — pynput 1.7.6 documentation

pynput Package Documentation This library allows you to control and monitor input devices. It contains subpackages for each type of input device supported: pynput.mouse Contains classes for controlling and monitoring a mouse or trackpad. pynput.keyboard Co

pynput.readthedocs.io

마우스, 키보드의 이벤트를 입력 받아 input_data 배열에 저장하는 함수를 정의

import time
from pynput import mouse, keyboard

input_data = []

def on_click(x, y, button, pressed):
    if pressed:
        event = f"Mouse Click: {button} at ({x}, {y})"
        input_data.append(event)
        print(f"{time.strftime('%H:%M:%S')} - {event}")

def on_scroll(x, y, dx, dy):
    event = f"Mouse Scroll: {dx}, {dy} at ({x}, {y})"
    input_data.append(event)
    print(f"{time.strftime('%H:%M:%S')} - {event}")

def on_key_press(key):
    try:
        event = f"Key Press: {key.char}"
    except AttributeError:
        event = f"Special Key Press: {key}"
    input_data.append(event)
    print(f"{time.strftime('%H:%M:%S')} - {event}")

입력이 완료되면, input_data 배열에 작성된 내용을 txt 형태로 만들어서 저장 하는 함수를 정의

import time
import os

def save_input_data():
    print("Recording was finished, now saving...")
    download_path = os.path.expanduser("~/Users/Downloads")
    current_time = time.strftime("%Y%m%d_%H%M%S")
    filename = os.path.join(download_path, f"recorded_actions_{current_time}.txt")
    
    with open(filename, "w") as file:
        for item in input_data:
            file.write(item + "\n")

    print(f"saved file name: {filename}")

위에 정의한 함수들을 이용해 입력 값을 받아 레코딩 하고, txt로 저장 할수 있게 명령어를 추가

mouse_listener = mouse.Listener(on_click=on_click, on_scroll=on_scroll)
keyboard_listener = keyboard.Listener(on_press=on_key_press)
mouse_listener.start()
keyboard_listener.start()

try:
    while True:
        time.sleep(0.1)
except KeyboardInterrupt:
    pass

mouse_listener.stop()
keyboard_listener.stop()
save_input_data()

실행 후 좌표 레코딩 확인

반응형