質問

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バインディングを作成しましょう!

他のヒント

このページ。 PythonとプラットフォームのQuartzライブラリ間のAppleの統合にフックする、 mousemove mouseclick のいくつかの関数を定義します。

このコードは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

geekorgy.com は、新しいバージョンのpythonをインストールしてからいくつかの障害に遭遇したことを除いて素晴らしいです。そこで、解決策を探しているかもしれない他の人へのいくつかのヒントがあります。

Mac OS 10.6にPython 2.7をインストールした場合、Quartz.CoreGraphicsからインポートするPythonを取得するいくつかのオプションがあります。

A)ターミナルで、 python のパスの前に python2.6 と入力します。スクリプト

B)次を実行すると、 PyObjCをインストールできます

  1. http://pypi.python.org/pypi/setuptools からeasy_installをインストールします
  2. ターミナルで、 which python と入力し、パスを 2.7
  3. までコピーします
  4. 次に、 easy_install&#8211; -prefix / Path / To / Python / Version pyobjc == 2.3 と入力します

    ** ie。 easy_install&#8211; -prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc == 2.3

  5. スクリプト内で、上部に import objc と入力します
  6. 初めてeasy_installが機能しない場合、最初にコアをインストールする必要があるかもしれません:

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

C)元のMac OS pythonに 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)

出典: 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 < code> 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!")

両方のコードブロックを1つのファイルに結合し、実行権限を付与して、シェルスクリプトとして実行できます。

最も簡単な方法は?コンパイル this 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 と入力して、プログラムをコンパイルします。コードよりもコメントの方が多いので、これをコンパイルする必要があるので怖がらないでください。これは、1つの簡単なタスクを実行する非常に短いプログラムです。


別の方法? pyobjc をインポートして、OSXフレームワークの一部にアクセスし、その方法でマウスにアクセスします。 (アイデアについては、最初の例のコードを参照してください。)

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top