Python을 사용하여 Mac에서 마우스를 제어하는 ​​방법은 무엇입니까?

StackOverflow https://stackoverflow.com/questions/281133

  •  07-07-2019
  •  | 
  •  

문제

OS X에서 Python을 사용하여 마우스를 이동하고 클릭 할 수있는 가장 쉬운 방법은 무엇입니까?

이것은 단지 빠른 프로토 타이핑을위한 것입니다. 우아 할 필요는 없습니다.

도움이 되었습니까?

해결책 3

Synergy의 소스 코드를 파헤쳐 마우스 이벤트를 생성하는 호출을 찾았습니다.

#include <ApplicationServices/ApplicationServices.h>

int to(int x, int y)
{
    CGPoint newloc;
    CGEventRef eventRef;
    newloc.x = x;
    newloc.y = y;

    eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
                                        kCGMouseButtonCenter);
    //Apparently, a bug in xcode requires this next line
    CGEventSetType(eventRef, kCGEventMouseMoved);
    CGEventPost(kCGSessionEventTap, eventRef);
    CFRelease(eventRef);

    return 0;
}

이제 파이썬 바인딩을 작성하십시오!

다른 팁

코드를 사용해보십시오 이 페이지. 몇 가지 기능을 정의하고 mousemove 그리고 mouseclick, Python과 플랫폼의 쿼츠 라이브러리 사이의 Apple의 통합에 연결됩니다.

이 코드는 10.6에서 작동하며 10.7에 사용하고 있습니다. 이 코드의 좋은 점은 일부 솔루션이없는 마우스 이벤트를 생성한다는 것입니다. 나는 그것을 사용하여 플래시 플레이어의 알려진 버튼 위치로 마우스 이벤트를 보내서 BBC IPLAYER를 제어합니다 (매우 취성). 특히 플래시 플레이어가 마우스 커서를 숨기지 않으므로 마우스 이동 이벤트가 필요합니다. 기능과 같은 기능 CGWarpMouseCursorPosition 이것을하지 않을 것입니다.

from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseUp
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGHIDEventTap

def mouseEvent(type, posx, posy):
        theEvent = CGEventCreateMouseEvent(
                    None, 
                    type, 
                    (posx,posy), 
                    kCGMouseButtonLeft)
        CGEventPost(kCGHIDEventTap, theEvent)

def mousemove(posx,posy):
        mouseEvent(kCGEventMouseMoved, posx,posy);

def mouseclick(posx,posy):
        # uncomment this line if you want to force the mouse 
        # to MOVE to the click location first (I found it was not necessary).
        #mouseEvent(kCGEventMouseMoved, posx,posy);
        mouseEvent(kCGEventLeftMouseDown, posx,posy);
        mouseEvent(kCGEventLeftMouseUp, posx,posy);

위 페이지의 코드 예는 다음과 같습니다.

##############################################################
#               Python OSX MouseClick
#       (c) 2010 Alex Assouline, GeekOrgy.com
##############################################################
import sys
try:
        xclick=intsys.argv1
        yclick=intsys.argv2
        try:
                delay=intsys.argv3
        except:
                delay=0
except:
        print "USAGE mouseclick [int x] [int y] [optional delay in seconds]"
        exit
print "mouse click at ", xclick, ",", yclick," in ", delay, "seconds"
# you only want to import the following after passing the parameters check above, because importing takes time, about 1.5s
# (why so long!, these libs must be huge : anyone have a fix for this ?? please let me know.)
import time
from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseDown
from Quartz.CoreGraphics import kCGEventLeftMouseUp
from Quartz.CoreGraphics import kCGMouseButtonLeft
from Quartz.CoreGraphics import kCGHIDEventTap
def mouseEventtype, posx, posy:
        theEvent = CGEventCreateMouseEventNone, type, posx,posy, kCGMouseButtonLeft
        CGEventPostkCGHIDEventTap, theEvent
def mousemoveposx,posy:
        mouseEventkCGEventMouseMoved, posx,posy;
def mouseclickposx,posy:
        #mouseEvent(kCGEventMouseMoved, posx,posy); #uncomment this line if you want to force the mouse to MOVE to the click location first (i found it was not necesary).
        mouseEventkCGEventLeftMouseDown, posx,posy;
        mouseEventkCGEventLeftMouseUp, posx,posy;
time.sleepdelay;
mouseclickxclick, yclick;
print "done."

이 코드를 시도해보십시오.

#!/usr/bin/python

import objc

class ETMouse():    
    def setMousePosition(self, x, y):
        bndl = objc.loadBundle('CoreGraphics', globals(), 
                '/System/Library/Frameworks/ApplicationServices.framework')
        objc.loadBundleFunctions(bndl, globals(), 
                [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])
        CGWarpMouseCursorPosition((x, y))

if __name__ == "__main__":
    et = ETMouse()
    et.setMousePosition(200, 200)

OSX Leopard 10.5.6에서 작동합니다

내가하고 싶을 때 설치했습니다 Jython 그리고 사용했습니다 java.awt.Robot 수업. Cpython 스크립트를 만들어야한다면 이것은 분명히 적합하지 않지만, 유연성을 선택할 때는 좋은 크로스 플랫폼 솔루션입니다.

import java.awt

robot = java.awt.Robot()

robot.mouseMove(x, y)
robot.mousePress(java.awt.event.InputEvent.BUTTON1_MASK)
robot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK)

그만큼 pynput 도서관은 현재 최고 수정 된 라이브러리처럼 보입니다. 입력 장치를 제어하고 모니터링 할 수 있습니다.

마우스 제어의 예는 다음과 같습니다.

from pynput.mouse import Button, Controller

mouse = Controller()

# Read pointer position
print('The current pointer position is {0}'.format(
    mouse.position))

# Set pointer position
mouse.position = (10, 20)
print('Now we have moved it to {0}'.format(
    mouse.position))

# Move pointer relative to current position
mouse.move(5, -5)

# Press and release
mouse.press(Button.left)
mouse.release(Button.left)

# Double click; this is different from pressing and releasing
# twice on Mac OSX
mouse.click(Button.left, 2)

# Scroll two steps down
mouse.scroll(0, 2)

가장 쉬운 방법은 pyautogui를 사용하는 것입니다.
예시:

  • 마우스 위치를 얻으려면 :

    >>> pyautogui.position()
    (187, 567)
    
  • 마우스를 특정 위치로 옮기려면 :

    >>> pyautogui.moveTo(100,200)
    
  • 마우스를 트리거하려면 다음을 클릭하십시오.

    >>> pyautogui.click()
    

자세한 세부 사항: Pyautogui

파이썬 스크립트 geekorgy.com 최신 버전의 Python을 설치 한 이후 몇 번의 걸림을 만났다는 점을 제외하고는 훌륭합니다. 다음은 해결책을 찾고있는 다른 사람들에게 몇 가지 팁입니다.

Mac OS 10.6에 Python 2.7을 설치 한 경우 Quartz.coreGraphics에서 Python을 가져 오는 몇 가지 옵션이 있습니다.

ㅏ) 터미널에서 유형 python2.6 그냥 대신 python 대본으로가는 길 전에

비) 당신은 할 수 있습니다 pyobjc를 설치하십시오 다음을 수행함으로써 :

  1. Easy_Install을 설치하십시오 http://pypi.python.org/pypi/setuplools
  2. 터미널에서 유형 which python 그리고 경로를 통과하십시오 2.7
  3. 그런 다음 입력하십시오 easy_install –-prefix /Path/To/Python/Version pyobjc==2.3

    **즉. easy_install –-prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc==2.3

  4. 스크립트 유형 내부 import objc 상단에
  5. Easy_Install이 처음 작동하지 않으면 먼저 코어를 설치해야 할 수도 있습니다.

    **즉. easy_install --prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc-core==2.3

씨) 당신은 할 수 있습니다 파이썬 경로를 재설정하십시오 원래 Mac OS Python에 :

  • 터미널에서 다음을 입력합니다. defaults write com.apple.versioner.python Version 2.6

*** 또한 화면에서 (x, y) 좌표를 찾는 빠른 방법 :

  1. 누르다 Command+Shift+4 (스크린 횡령 선택)
  2. 그런 다음 커서가 좌표를 보여줍니다
  3. 그런 다음 ESC를 치고 벗어나십시오.

가장 좋은 방법은 사용하는 것입니다 오토피 패키지. 사용하기가 매우 간단하고 부팅 크로스 플랫폼입니다.

커서를 위치로 옮기려면 (200,200) :

import autopy
autopy.mouse.move(200,200)

사용 CoreGraphics Quartz 라이브러리에서 예를 들어 :

from Quartz.CoreGraphics import CGEventCreate
from Quartz.CoreGraphics import CGEventGetLocation
ourEvent = CGEventCreate(None);
currentpos = CGEventGetLocation(ourEvent);
mousemove(currentpos.x,currentpos.y)

원천: Geekorgy 페이지에서 Tony Comment.

다음은 사용한 완전한 예입니다 Quartz 도서관:

#!/usr/bin/python
import sys
from AppKit import NSEvent
import Quartz

class Mouse():
    down = [Quartz.kCGEventLeftMouseDown, Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown]
    up = [Quartz.kCGEventLeftMouseUp, Quartz.kCGEventRightMouseUp, Quartz.kCGEventOtherMouseUp]
    [LEFT, RIGHT, OTHER] = [0, 1, 2]

    def position(self):
        point = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) )
        return point.x, point.y

    def location(self):
        loc = NSEvent.mouseLocation()
        return loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y

    def move(self, x, y):
        moveEvent = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, (x, y), 0)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, moveEvent)

    def press(self, x, y, button=1):
        event = Quartz.CGEventCreateMouseEvent(None, Mouse.down[button], (x, y), button - 1)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)

    def release(self, x, y, button=1):
        event = Quartz.CGEventCreateMouseEvent(None, Mouse.up[button], (x, y), button - 1)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)

    def click(self, button=LEFT):
        x, y = self.position()
        self.press(x, y, button)
        self.release(x, y, button)

    def click_pos(self, x, y, button=LEFT):
        self.move(x, y)
        self.click(button)

    def to_relative(self, x, y):
        curr_pos = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) )
        x += current_position.x;
        y += current_position.y;
        return [x, y]

    def move_rel(self, x, y):
        [x, y] = to_relative(x, y)
        moveEvent = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, Quartz.CGPointMake(x, y), 0)
        Quartz.CGEventPost(Quartz.kCGHIDEventTap, moveEvent)

위의 코드는 이러한 원본 파일을 기반으로합니다. Mouse.pymouseUtils.py.

위의 클래스를 사용하는 데모 코드는 다음과 같습니다.

# DEMO
if __name__ == '__main__':
    mouse = Mouse()
    if sys.platform == "darwin":
        print("Current mouse position: %d:%d" % mouse.position())
        print("Moving to 100:100...");
        mouse.move(100, 100)
        print("Clicking 200:200 position with using the right button...");
        mouse.click_pos(200, 200, mouse.RIGHT)
    elif sys.platform == "win32":
        print("Error: Platform not supported!")

두 코드 블록을 하나의 파일로 결합하고 실행 권한을 제공하고 쉘 스크립트로 실행할 수 있습니다.

가장 쉬운 방법? 엮다 이것 코코아 앱과 마우스 움직임을 전달하십시오.

코드는 다음과 같습니다.

// File:
// click.m
//
// Compile with:
// gcc -o click click.m -framework ApplicationServices -framework Foundation
//
// Usage:
// ./click -x pixels -y pixels
// At the given coordinates it will click and release.

#import <Foundation/Foundation.h>
#import <ApplicationServices/ApplicationServices.h>

int main(int argc, char **argv) {
  NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  NSUserDefaults *args = [NSUserDefaults standardUserDefaults];


  // grabs command line arguments -x and -y
  //
  int x = [args integerForKey:@"x"];
  int y = [args integerForKey:@"y"];

  // The data structure CGPoint represents a point in a two-dimensional
  // coordinate system.  Here, X and Y distance from upper left, in pixels.
  //
  CGPoint pt;
  pt.x = x;
  pt.y = y;


  // https://stackoverflow.com/questions/1483567/cgpostmouseevent-replacement-on-snow-leopard
  CGEventRef theEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, pt, kCGMouseButtonLeft);
  CGEventSetType(theEvent, kCGEventLeftMouseDown);
  CGEventPost(kCGHIDEventTap, theEvent);
  CFRelease(theEvent);

  [pool release];
  return 0;
}

CGPOSTMOUSEEEVENT CGREMOTEOPERATION.H 헤더 파일에서 CGPOSTMOUSEEVENT를 호출하는 클릭이라는 앱. 조정은 명령 줄 인수로 조정을 취하고 마우스를 해당 위치로 이동 한 다음 마우스 버튼을 클릭하고 공개합니다.

위의 코드를 Click.m으로 저장하고 터미널을 열고 소스를 저장 한 폴더로 전환하십시오. 그런 다음 입력하여 프로그램을 컴파일하십시오 gcc -o click click.m -framework ApplicationServices -framework Foundation. 코드보다 더 많은 주석이 있으므로 이것을 컴파일해야함으로써 협박하지 마십시오. 하나의 간단한 작업을 수행하는 매우 짧은 프로그램입니다.


또 다른 방법? 수입 pyobjc 일부 OSX 프레임 워크에 액세스하고 마우스에 액세스하려면 마우스에 액세스하십시오. (아이디어의 첫 번째 예제의 코드를 참조하십시오).

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top