Can I use Python to capture keyboard and mouse events in OSX?

牧云@^-^@ 提交于 2019-12-03 06:16:03
synthesizerpatel

I ran across a few solutions to this problem today and figured I'd circle back around and share here so others could save the search time.

A nifty cross platform solution for simulating keyboard and mouse input: http://www.autopy.org/

I also found a brief but working (As of Mountain Lion) example of how to globally log key strokes. The only caveat is that you have to use Python2.6 as 2.7 doesn't seem to have the objc modules available.

#!/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()

For mouse input, simply replace NSKeyDownMask with the relevant mask from the list available here: http://developer.apple.com/library/mac/#documentation/cocoa/Reference/ApplicationKit/Classes/NSEvent_Class/Reference/Reference.html#//apple_ref/occ/clm/NSEvent/addGlobalMonitorForEventsMatchingMask:handler:

For example, NSMouseMovedMask works for tracking mouse movements. From there, you can access event.locationInWindow() or other attributes.

Calvin Cheng

Here's a solution without using curses:

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

This question was asked some time back here - Python cross-platform listening for keypresses?

You might find the sample code there helpful!

I know that you can use curses for capturing key input, but im not sure about mouse input. Not only that but if im not mistaken it is included in the std library with 2.7.2.

There doesn't seem to be a way of doing this in Python on OSX.

0x8BADF00D

Calvin Cheng, Thank you. your suggestion works on OS X 10.8.5.

Code from 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)

One more solution Key Listeners in python?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!