我正在尝试在Python中为OSX编写一个简单的宏录制器 - 当脚本在后台运行并重放它们时,它可以捕获鼠标和键事件。我可以使用autopy作为后者,前者是否有类似的简单库?
答案 0 :(得分:6)
今天我遇到了一些针对这个问题的解决方案,并认为我会回过头来分享这里,以便其他人可以节省搜索时间。
用于模拟键盘和鼠标输入的漂亮的跨平台解决方案:http://www.autopy.org/
我还发现了一个简短但有效的(如山狮之类)如何全局记录击键的示例。唯一需要注意的是你必须使用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()或其他属性。
答案 1 :(得分:2)
这是一个不使用curses
的解决方案:
http://docs.python.org/faq/library.html#how-do-i-get-a-single-keypress-at-a-time
这个问题在这里被问了一段时间 - Python cross-platform listening for keypresses?
您可能会发现示例代码有用!
答案 2 :(得分:1)
我知道您可以使用curses
来捕获键输入,但我不确定鼠标输入。不仅如此,如果我没有弄错,它将被包含在带有2.7.2的std库中。
答案 3 :(得分:-1)
似乎没有办法在OSX上的Python中执行此操作。
答案 4 :(得分:-2)
来自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?