파이썬에서 pyautogui를 이용한 마우스와 키보드 제어

모듈 설치

Windows: 추가 설치 불필요
macOS: sudo pip3 install pyobjc-core pyobjc-framework-Quartz
Ubuntu: sudo apt-get install scrot python3-tk python3-dev && sudo pip3 install python3-xlib
설치: pip install pyautogui (모든 OS)

안전 주의사항

긴급 중단: Ctrl-Alt-Del(Windows/Linux) 또는 ⌘-Shift-Option-Q(macOS)
실행 간격 설정: pyautogui.PAUSE = 1.5 (초 단위 지연)
안전 장치: pyautogui.FAILSAFE = True 활성화 시 좌상단 모서리로 커서 이동하면 FailSafeException 발생

마우스 제어

화면 크기: width, height = pyautogui.size()
절대 이동: pyautogui.moveTo(x, y, duration=초)
상대 이동: pyautogui.moveRel(dx, dy, duration=초)
클릭: pyautogui.click(x, y, button='left')
pyautogui.doubleClick() | pyautogui.rightClick()

# 커서 위치 실시간 추적
import pyautogui
try:
    while True:
        x, y = pyautogui.position()
        print(f"X:{x:4} Y:{y:4}", end='\r')
except KeyboardInterrupt:
    print("\n종료")

드래그 및 스크롤

절대 드래그: pyautogui.dragTo(x, y, duration=초)
상대 드래그: pyautogui.dragRel(dx, dy, duration=초)
스크롤: pyautogui.scroll(단위) (양수: 위, 음수: 아래)

# 나선형 드로잉 예제
import pyautogui, time
time.sleep(3)
pyautogui.click()
step = 200
while step > 10:
    pyautogui.dragRel(step, 0, 0.1)
    pyautogui.dragRel(0, step, 0.1)
    step -= 20
    pyautogui.dragRel(-step, 0, 0.1)
    pyautogui.dragRel(0, -step, 0.1)
    step -= 20

화면 처리

스크린샷: screenshot = pyautogui.screenshot()
픽셀 확인: pyautogui.pixelMatchesColor(x, y, (R,G,B))
이미지 검색: position = pyautogui.locateOnScreen('image.png')
all_positions = list(pyautogui.locateAllOnScreen('image.png'))

키보드 제어

텍스트 입력: pyautogui.typewrite('텍스트', interval=0.1)
특수 키: pyautogui.press(['enter','tab','esc'])
조합 키: pyautogui.hotkey('ctrl', 'c')

클립보드 제어

import pyperclip
pyperclip.copy('복사할 텍스트')
contents = pyperclip.paste()

주요 함수 요약

함수설명
moveTo(x,y)절대 좌표 이동
moveRel(dx,dy)상대 위치 이동
dragTo(x,y)드래그 이동
click()클릭 동작
scroll(n)스크롤
typewrite(text)키 입력
hotkey(k1,k2)단축키 실행
screenshot()화면 캡처

태그: python pyautogui 자동화 마우스제어 키보드제어

6월 6일 17:53에 게시됨