2012-03-26 101 views
9

我想在Python中爲OSX寫一個簡單的宏記錄器 - 當腳本在後臺運行並重播它們時,它可以捕獲鼠標和鍵盤事件。後者可以使用autopy,前者有沒有類似的簡單庫?我可以使用Python捕獲OSX中的鍵盤和鼠標事件嗎?

+0

這裏所提到的一些包有OS X的支持(例如'keyboard'):https://stackoverflow.com/questions/11918999/key -listeners合蟒/ – 2017-10-28 20:05:36

回答

0

在OSX上似乎沒有辦法在Python上這樣做。

1

我知道你可以使用curses來捕獲按鍵輸入,但我不確定鼠標輸入。不僅如此,但如果我沒有把它誤認爲包含在2.7.2的std庫中。

5

今天我遇到了這個問題的幾個解決方案,並認爲我會回過頭來分享一下,這樣其他人可以節省搜索時間。

模擬鍵盤和鼠標輸入一個漂亮的跨平臺解決方案: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() 

對於鼠標輸入,簡單地從可用這裏的列表中選擇相關面膜代替NSKeyDownMaskhttp://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

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) 

還有一個解決方案 Key Listeners in python?

相關問題