我能使用Python在OSX系统中捕获键盘和鼠标事件吗?

13

我试图在Mac OSX中使用Python编写一个简单的宏记录器 - 可以在后台捕捉鼠标和键盘事件并重放。我可以使用autopy进行后者,是否有类似简单的库可以用于前者?


这里提到的一些包有OS X支持(例如keyboard):https://dev59.com/HWct5IYBdhLWcg3wqfL9 - Anton Tarasenko
5个回答

6
我今天找到了一些解决这个问题的方法,想在这里分享一下,以便其他人节省搜索时间。
一个非常方便的跨平台解决方案,可以模拟键盘和鼠标输入: http://www.autopy.org/
我还找到了一个简短但有效(适用于Mountain Lion)的示例,可以全局记录按键。唯一需要注意的是,您必须使用Python2.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

1

我知道你可以使用 curses 来捕获键盘输入,但是关于鼠标输入我不太确定。而且如果我没记错的话,它已经在 2.7.2 的 std 库中包含了。


-1

在 macOS 上似乎没有一种方法可以用 Python 来实现这个。


-2

Calvin Cheng,非常感谢。您的建议在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)

另一种解决方案Python中的键监听器?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接