在OS X上使用Python移动鼠标(并可能单击)的最简单方法是什么?
这仅适用于快速原型设计,它不一定非常优雅.
解决方法:
尝试this page的代码.它定义了几个函数,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."