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

现在编写Python绑定!

其他提示

尝试此页面。它定义了一些函数, mousemove mouseclick ,它们与Apple在Python和平台的Quartz库之间的集成有关。

此代码适用于10.6,我在10.7上使用它。这段代码的好处在于它会生成鼠标事件,而某些解决方案却没有。我通过将鼠标事件发送到他们的Flash播放器中的已知按钮位置来控制BBC iPlayer(我知道非常脆弱)。特别是鼠标移动事件是必需的,否则Flash播放器永远不会隐藏鼠标光标。像 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

python 脚本来自 极客网 很棒,除了我安装了较新版本的 python 后遇到了一些障碍。因此,这里为其他可能正在寻找解决方案的人提供了一些提示。

如果您在 Mac OS 10.6 上安装了 Python 2.7,您有几个选项可以让 python 从 Quartz.CoreGraphics 导入:

A) 在航站楼中, 类型 python2.6 而不是仅仅 python 在脚本路径之前

二) 你可以 安装 PyObjC 通过执行以下操作:

  1. 安装 easy_install 从 http://pypi.python.org/pypi/setuptools
  2. 在终端中,输入 which python 并复制路径向上 2.7
  3. 然后输入 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. 在脚本类型里面 import objc 在顶部
  5. 如果 easy_install 第一次不起作用,您可能需要先安装核心:

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

C) 你可以 重置你的Python路径 原始 Mac OS python:

  • 在终端中,输入: defaults write com.apple.versioner.python Version 2.6

***此外,还有一种快速查找屏幕上 (x,y) 坐标的方法:

  1. Command+Shift+4 (屏幕抓取选择)
  2. 然后光标显示坐标
  3. 然后按 Esc 键退出。

您最好的选择是使用 AutoPy包。它使用起来非常简单,并且可以跨平台启动。

将光标移动到位置(200,200):

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

使用Quartz库中的 CoreGraphics ,例如:

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

来源: Tony在Geekorgy页面发表评论

以下是使用 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.py <代码> mouseUtils.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!")

您可以将两个代码块合并为一个文件,提供执行权限并将其作为shell脚本运行。

最简单的方法?编译 Cocoa应用程序并将鼠标移动传递给它。

以下是代码:

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

应用程序调用click,从CGRemoteOperation.h头文件调用CGPostMouseEvent。它将坐标作为命令行参数,将鼠标移动到该位置,然后单击并释放鼠标按钮。

     

将上述代码保存为click.m,打开终端,然后切换到保存源的文件夹。然后键入 gcc -o click click.m -framework ApplicationServices -framework Foundation 来编译程序。不要因为需要编译它而感到恐惧,因为有更多的注释而不是代码。这是一个非常简短的程序,可以执行一项简单的任务。


另一种方式?导入 pyobjc 以访问某些OSX框架并以此方式访问鼠标。 (请参阅第一个示例中的代码)。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top