Jak sterować myszą w Macu za pomocą Pythona?

Jaki byłby najprostszy sposób poruszania myszką (i ewentualnie klikania) przy użyciu Pythona na OS X?

To tylko do szybkiego prototypowania, nie musi być eleganckie.

Author: kenorb, 2008-11-11

11 answers

Wypróbuj kod na tej stronie . Definiuje on kilka funkcji, mousemove i mouseclick, które łączą się z integracją Apple między Pythonem a bibliotekami Quartz.

Ten kod działa na 10.6, a ja używam go na 10.7. Fajną rzeczą w tym kodzie jest to, że generuje zdarzenia myszy, czego niektóre rozwiązania nie robią. używam go do sterowania BBC iPlayer wysyłając zdarzenia myszy do znanych pozycji przycisków w ich odtwarzaczu Flash (bardzo kruche wiem). Zdarzenia poruszania myszką, w szczególnie, są wymagane, ponieważ w przeciwnym razie Flash player nigdy nie ukrywa kursor myszy. Funkcje takie jak CGWarpMouseCursorPosition tego nie zrobią.

from Quartz.CoreGraphics import CGEventCreateMouseEvent
from Quartz.CoreGraphics import CGEventPost
from Quartz.CoreGraphics import kCGEventMouseMoved
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);

Oto przykład kodu z powyższej strony:

##############################################################
#               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."
 28
Author: Mike Rhodes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2021-02-04 23:15:13

The pynput biblioteka wydaje się najlepszą obecnie utrzymywaną biblioteką. Umożliwia sterowanie i monitorowanie urządzeń wejściowych.

Oto przykład sterowania myszą:

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)
 16
Author: GJ.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-26 13:12:39

Po prostu spróbuj tego kodu:

#!/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)

Działa w OSX leopard 10.5.6

 11
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-03-19 23:15:07

Najprostszym sposobem jest użycie PyAutoGUI.

Instalacja:

pip install pyautogui

Przykłady:

  • Aby uzyskać pozycję myszy:

    >>> pyautogui.position()
    (187, 567)
    
  • Aby przesunąć mysz do określonej pozycji:

    >>> pyautogui.moveTo(100,200)
    
  • Aby wywołać kliknięcie myszką:

    >>> pyautogui.click()
    

Więcej Szczegółów: PyAutoGUI

 11
Author: biendltb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2020-12-21 04:18:46

Przekopałem się przez kod źródłowy Synergy, aby znaleźć wywołanie generujące zdarzenia myszy:

#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;
}

Teraz pisać wiązania Pythona!

 9
Author: Ben,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2008-12-31 06:16:41

Kiedy chciałem to zrobić, zainstalowałem Jython i użyłem java.awt.Robot klasy. Jeśli chcesz zrobić skrypt CPython, to oczywiście nie jest to odpowiednie, ale gdy masz elastyczność wyboru czegokolwiek, jest to ładne rozwiązanie wieloplatformowe.

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)
 8
Author: Jeremy,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-10 15:21:40

Najlepiej skorzystać z pakietu AutoPy . Jest niezwykle prosty w użyciu i wieloplatformowy do rozruchu.

Aby przesunąć kursor do pozycji (200,200):

import autopy
autopy.mouse.move(200,200)
 2
Author: Gwen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-10 18:49:19

Skrypt Pythona z geekorgy.com jest świetny, z tym, że napotkałem kilka problemów, odkąd zainstalowałem nowszą wersję Pythona. Oto kilka wskazówek dla innych, którzy mogą szukać rozwiązania.

Jeśli zainstalowałeś Pythona 2.7 Na Mac OS 10.6, masz kilka opcji, aby zaimportować Pythona z Quartz.CoreGraphics:

A) w terminalu, wpisz python2.6 zamiast tylko python przed ścieżką do skryptu

B) Możesz zainstaluj PyObjC wykonując następujące czynności:

  1. zainstaluj easy_install z http://pypi.python.org/pypi/setuptools
  2. w terminalu wpisz which python i skopiuj ścieżkę do 2.7
  3. Następnie wpisz easy_install –-prefix /Path/To/Python/Version pyobjc==2.3

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

  4. wewnątrz typu skryptu import objc u góry
  5. Jeśli easy_install nie działa za pierwszym razem, możesz najpierw zainstalować rdzeń:

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

C) Możesz zresetować ścieżkę Pythona do oryginalnego Pythona Mac OS:

  • w terminalu wpisz: defaults write com.apple.versioner.python Version 2.6

* * * również, szybki sposób, aby dowiedzieć się (X, y) współrzędne na ekranie:

  1. Naciśnij Command+Shift+4 (Screen grab selection)
  2. kursor pokazuje współrzędne
  3. następnie naciśnij Esc, aby się z tego wydostać.
 1
Author: dfred,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-22 05:51:10

Użyj CoreGraphics z biblioteki Quartz, na przykład:

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

Źródło: Tony komentarz na stronie Geekorgy .

 0
Author: kenorb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-26 13:25:29

Oto pełny przykład użycia biblioteki 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)

powyższy kod jest oparty na tych oryginalnych plikach: Mouse.pymouseUtils.py.

Oto kod demonstracyjny używający powyższej klasy:

# 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!")

Możesz połączyć oba bloki kodu w jeden plik, dać pozwolenie na wykonanie i uruchomić go jako skrypt powłoki.

 0
Author: kenorb,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-28 18:26:22

Najprostszy sposób? Skompiluj aplikację Cocoa i podaj jej ruchy myszką.

Oto kod:

// 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;
}

Aplikacja o nazwie click, która wywołuje CGPostMouseEvent z CGRemoteOperation.plik nagłówkowy H. Pobiera współrzędne jako argumenty wiersza poleceń, przesuwa mysz do tej pozycji, a następnie klika i zwalnia przycisk myszy.

Zapisz powyższy kod jako kliknięcie.M, otwórz Terminal i przełącz się do folderu, w którym zapisałeś źródło. Następnie skompiluj program po wpisaniu gcc -o click click.m -framework ApplicationServices -framework Foundation. Nie daj się zastraszyć potrzebą kompilacji, ponieważ jest więcej komentarzy niż kodu. Jest to bardzo krótki program, który wykonuje jedno proste zadanie.


W inny sposób? Zaimportuj pyobjc , Aby uzyskać dostęp do niektórych frameworków OSX i uzyskać dostęp do myszy w ten sposób. (zobacz kod z pierwszego przykładu dla pomysłów).
 0
Author: Rizwan Kassim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-26 00:32:38