3

I'm trying to get window handles to currently available windows using PyObjC, with Mac OS X 10.7 and default Python 2.7. However, the following 2-liner causes Python to crash immediately. What gives?

bash-3.2$ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from AppKit import *
>>> NSCountWindows(None)
Bus error: 10
bash-3.2$

The thread stack trace didn't help that much:

Thread 0 Crashed:: Dispatch queue: com.apple.main-thread
0   libsystem_c.dylib               0x91167c19 _spin_lock$VARIANT$mp + 9
1   com.apple.CoreGraphics          0x990d0048 CGSGetOnScreenWindowCount + 87
2   com.apple.AppKit                0x9bdd13fd NSCountWindows + 61
... (Python internal calls)
Jerry Chong
  • 563
  • 2
  • 9
  • 19
  • I never got PyObjC to work in 10.7, I'm very curious if we can figure out what is causing it, I haven't had much time to go diving into it. – lukecampbell Apr 26 '12 at 19:46
  • For the record, I've since modified my approach to instead run my Python code that operates on Cocoa windows encapsulated as a callback inside a simple NSApp().run() - still curious if it's possible to run PyObjC code within the whole NSApp gamut though. :P – Jerry Chong May 09 '12 at 10:37

1 Answers1

2

Apple's frameworks don't particularly like when you use them without setting up an Application object. The corresponding C code also crashes:

#import <AppKit/AppKit.h>
#include <stdio.h>

int main(void)
{
   long windows;

   NSCountWindows(&windows);
   printf("%d\n", (int)windows);
   return 0;
}

The easiest workaround is to create an NSApplication object before calling APIs:

import AppKit

AppKit.NSApplication.sharedApplication()
print AppKit.NSCountWindows(None)
Ronald Oussoren
  • 2,715
  • 20
  • 29