2012-03-26 9 views
9

私はPython for OSXで簡単なマクロレコーダーを書こうとしています。スクリプトはバックグラウンドで実行され、再生されるので、マウスやキーイベントをキャプチャできます。私は後者のためにautopyを使うことができます、前者には同様の単​​純なライブラリがありますか?OSXでPythonを使用してキーボードとマウスのイベントをキャプチャできますか?

+0

いくつかのパッケージは、OS Xのサポート(例えば、 'keyboard')があります。https://stackoverflow.com/questions/11918999/keyを-listeners-in-python / –

答えて

0

OSXでPythonでこれを行う方法はないようです。

1

cursesをキー入力のキャプチャに使用できますが、マウス入力についてはわかりません。それだけでなく、誤解されていなければ2.7.2のstdライブラリに含まれています。

5

今日この問題の解決策をいくつか見つけ出し、私はここで回り回って共有して、他の人が検索時間を節約できると考えました。

キーボードやマウスの入力をシミュレートするための気の利いたクロスプラットフォームソリューション:http://www.autopy.org/

私はまた、簡単に見つかりましたが(マウンテンライオンの通り)のキーストロークを記録グローバルにする方法の例を取り組んでいます。唯一の注意点は、Python 2.6を使用しなければならないということです.2.7はobjcモジュールを利用できないようです。

#!/usr/bin/python2.6 

"""PyObjC keylogger for Python 
by ljos https://github.com/ljos 
""" 

from Cocoa import * 
import time 
from Foundation import * 
from PyObjCTools import AppHelper 

class AppDelegate(NSObject): 
    def applicationDidFinishLaunching_(self, aNotification): 
     NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler) 

def handler(event): 
    NSLog(u"%@", event) 

def main(): 
    app = NSApplication.sharedApplication() 
    delegate = AppDelegate.alloc().init() 
    NSApp().setDelegate_(delegate) 
    AppHelper.runEventLoop() 

if __name__ == '__main__': 
    main() 

マウス入力の場合は、単にここで使用可能なリストから関連するマスクでNSKeyDownMaskを置き換える:http://developer.apple.com/library/mac/#documentation/cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/Reference/Reference.html#//apple_ref/occ/clm/NSEvent/addGlobalMonitorForEventsMatchingMask:handler:マウスの動きを追跡するための

例えば

NSMouseMovedMask作品を。 そこから、event.locationInWindow()または他の属性にアクセスできます。

-2

カルバン・チェン、ありがとう。あなたの提案はOS X 10.8.5で動作します。

コードhttp://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time

#!/usr/bin/python 

import termios, fcntl, sys, os 

fd = sys.stdin.fileno() 

oldterm = termios.tcgetattr(fd) 
newattr = termios.tcgetattr(fd) 
newattr[3] = newattr[3] & ~termios.ICANON & ~termios.ECHO 
termios.tcsetattr(fd, termios.TCSANOW, newattr) 

oldflags = fcntl.fcntl(fd, fcntl.F_GETFL) 
fcntl.fcntl(fd, fcntl.F_SETFL, oldflags | os.O_NONBLOCK) 

try: 
    while 1: 
     try: 
      c = sys.stdin.read(1) 
      print "Got character", repr(c) 
     except IOError: pass 
finally: 
    termios.tcsetattr(fd, termios.TCSAFLUSH, oldterm) 
    fcntl.fcntl(fd, fcntl.F_SETFL, oldflags) 

つ以上の溶液からここで言及 Key Listeners in python?

関連する問題