كيفية التحكم في الماوس في ماك باستخدام بايثون؟
سؤال
ما هي أسهل طريقة لتحريك الماوس (وربما النقر) باستخدام Python على OS X؟
هذا فقط من أجل النماذج الأولية السريعة، وليس من الضروري أن تكون أنيقة.
المحلول 3
وأنا حفرت خلال التعليمات البرمجية المصدر من التآزر للعثور على الدعوة التي تولد أحداث الماوس:
#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
، الذي ربط إلى التكامل بين أبل بيثون والمكتبات الكوارتز للمنبر.
وهذا الرمز يعمل على 10.6، وأنا استخدامه على 10.7. والشيء الجميل في هذا الرمز هو أنه يولد أحداث الماوس، التي بعض الحلول لا. أنا استخدامها للسيطرة على بي بي سي 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 10.5.6 نمر
وعندما أردت أن تفعل ذلك، أنا ركبت جيثون و تستخدم في java.awt.Robot
الصف. إذا كنت بحاجة إلى جعل السيناريو سي بايثون من الواضح أن هذا غير مناسب، ولكن عندما لك المرونة لاختيار أي شيء غير لطيف الحل عبر منصة.
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 2.7 على نظام التشغيل Mac OS 10.6 لديك بعض الخيارات لاستيراد لغة python من Quartz.CoreGraphics:
أ) في المحطة، يكتب python2.6
بدلا من مجرد python
قبل المسار إلى البرنامج النصي
ب) أنت تستطيع قم بتثبيت PyObjC عن طريق القيام بما يلي:
- قم بتثبيت easy_install من http://pypi.python.org/pypi/setuptools
- في المحطة، اكتب
which python
ونسخ المسار من خلال2.7
ثم اكتب
easy_install –-prefix /Path/To/Python/Version pyobjc==2.3
**أي.
easy_install –-prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc==2.3
- داخل نوع البرنامج النصي
import objc
في القمة إذا لم يعمل 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) على الشاشة:
- يضعط
Command+Shift+4
(اختيار التقاط الشاشة) - ثم يظهر المؤشر الإحداثيات
- ثم اضغط على Esc للخروج منه.
وأفضل رهان هو استخدام حزمة AutoPy . انها بسيطة جدا للاستخدام، وعبر منصة التمهيد.
لنقل المؤشر إلى موقف (200200):
import autopy
autopy.mouse.move(200,200)
استخدم CoreGraphics
من مكتبة كوارتز، على سبيل المثال:
from Quartz.CoreGraphics import CGEventCreate
from Quartz.CoreGraphics import CGEventGetLocation
ourEvent = CGEventCreate(None);
currentpos = CGEventGetLocation(ourEvent);
mousemove(currentpos.x,currentpos.y)
<سوب> المصدر: <لأ href = "http://web.archive.org/web/20120417231126/http://www.geekorgy.com:80/index.php/2010/06/python-mouse -click-وتحرك الماوس في والتفاح ماك-سكس-الثلوج الفهد 10-6-س / "يختلط =" نوفولو noreferrer "> توني تعليق في الصفحة 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)
في فوق الكود هو بناء على هذه الملفات الأصلية: <لأ href = "https://github.com/MichaelLeith/pyInputSim/blob/master/src/OSX/Mouse.py" يختلط = "نوفولو noreferrer" > 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!")
ويمكنك الجمع بين كتل التعليمات البرمجية في ملف واحد، وإعطاء إذن التنفيذ وتشغيله كبرنامج نصي قذيفة.
وأسهل طريقة؟ تجميع هذا التطبيق الكاكاو وتمر عليه حركات الماوس الخاص بك.
وهنا هو رمز:
// 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;
}
<اقتباس فقرة>
والتطبيقات دعا فوق ذلك استدعاء CGPostMouseEvent من ملف الرأس CGRemoteOperation.h. يستغرق إحداثيات كوسائط سطر الأوامر، يتحرك الماوس لهذا الموقف، ثم نقر والنشرات زر الماوس.
وحفظ التعليمات البرمجية أعلاه كما click.m، ومحطة مفتوحة، والتبديل إلى المجلد حيث قمت بحفظ المصدر. ثم ترجمة البرنامج عن طريق كتابة gcc -o click click.m -framework ApplicationServices -framework Foundation
. لا يرهبها الحاجة إلى تجميع هذا كما أن هناك المزيد من التعليقات من التعليمات البرمجية. وهو برنامج قصير جدا التي لا مهمة واحدة بسيطة.
وهناك طريقة أخرى؟ استيراد pyobjc للوصول إلى بعض إطار OSX والوصول إلى الماوس على هذا النحو. (راجع التعليمات البرمجية من المثال الأول للأفكار).