Skip to content

Instantly share code, notes, and snippets.

@cuilkid
Created June 29, 2012 22:06
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cuilkid/3020934 to your computer and use it in GitHub Desktop.
Save cuilkid/3020934 to your computer and use it in GitHub Desktop.
from Cocoa import NSApp, NSEvent, NSKeyDownMask # , NSApplication
from Foundation import NSObject, NSLog
from PyObjCTools import AppHelper
from AppKit import NSApplication
# https://bitbucket.org/ronaldoussoren/pyobjc/
# you have to enable access for assistive devices in 'System Preferences>Universal Access>Keyboard'
class AppDelegate(NSObject):
def applicationDidFinishLaunching_(self, notification):
print 'A'
NSEvent.addGlobalMonitorForEventsMatchingMask_handler_(NSKeyDownMask, handler)
print 'B'
def handler(event):
try:
print 'C'
NSLog(u"%@", event)
print 'D'
except KeyboardInterrupt:
AppHelper.stopEventLoop()
def main():
app = NSApplication.sharedApplication()
delegate = AppDelegate.alloc().init()
NSApp().setDelegate_(delegate)
print 'E'
AppHelper.runEventLoop()
if __name__ == '__main__':
main()
@ljos
Copy link

ljos commented Jun 29, 2012

It is the handler(self,event)
remove self and only have handler(event)

This is because of how pyObjC handles the function.

@cuilkid
Copy link
Author

cuilkid commented Jun 29, 2012

My mistake for making handler a method of AppDelegate class, it should be it's own function (fixed).

@ljos
Copy link

ljos commented Jun 29, 2012

Yes. AppDelegate does not like it. (I am a bit unsure of why.) You could have had a handler that was part of a different object though.

so

  class Test:
    def handler(self, event):
        print event

this handler should be usable.

@cuilkid
Copy link
Author

cuilkid commented Jun 29, 2012

I still see the same error though. type 'exceptions.TypeError': Argument 3 is a block, but no signature available

any ideas?

@ljos
Copy link

ljos commented Jun 29, 2012

Your code works for me now. I'm on Python2.7 and using the pyobjc in the link you have above.

I am however not able to send KeyboardInterrupt to abort the process.

@cuilkid
Copy link
Author

cuilkid commented Jun 29, 2012

I installed Python2.7 and now none of the imports work...

Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.

from Foundation import NSObject, NSLog
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named Foundation
from PyObjCTools import AppHelper
Traceback (most recent call last):
File "", line 1, in
ImportError: No module named PyObjCTools

@ljos
Copy link

ljos commented Jun 30, 2012

You need to install the dependencies again for python2.7

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment