def test_isPythonException(self): try: a = objc.lookUpClass("NSArray").array() a.objectAtIndex_(42) except Exception as exc: self.assertFalse(Debugging.isPythonException(exc)) else: self.fail("Exception not raised") try: cls = objc.lookUpClass("NSException") cls.exceptionWithName_reason_userInfo_("FooBar", "hello world", None).raise__() except Exception as exc: self.assertFalse(Debugging.isPythonException(exc)) else: self.fail("Exception not raised") try: a = [] a[42] except Exception as exc: self.assertTrue(Debugging.isPythonException(exc))
def applicationDidFinishLaunching_(self, notification): if debug_mode: Debugging.installPythonExceptionHandler() self.reg = Registry() self.the_account = Account(self.reg, read_config()) self._set_up_ui() self.the_account.update_if_needed()
def test_isPythonException(self): try: a = objc.lookUpClass('NSArray').array() a.objectAtIndex_(42) except Exception as exc: self.assertFalse(Debugging.isPythonException(exc)) try: a = [] a[42] except Exception as exc: self.assertTrue(Debugging.isPythonException(exc))
def show(self): pool = NSAutoreleasePool.alloc().init() Debugging.installVerboseExceptionHandler() AppHelper.installMachInterrupt() self.window.orderFrontRegardless() print time.ctime(), "Cocoa: Starting event loop..." try: NSApp().run() except KeyboardInterrupt: print time.ctime(), "Interrupted." finally: print time.ctime(), "Cocoa: Event loop ended." del pool
def close(self): pool = NSAutoreleasePool.alloc().init() self.window.orderOut_(None) # quit app mainloop and hide window if NSApp().isRunning() == objc.YES: print time.ctime(), "Cocoa: Pausing app..." NSApp().stop_(None) # needs a pseudo-event before it'll be correctly stopped e = NSEvent.otherEventWithType_location_modifierFlags_timestamp_windowNumber_context_subtype_data1_data2_(\ NSApplicationDefined, NSMakePoint(0, 0), 0, 0.0, 0, None, 0, 0, 0) NSApp().postEvent_atStart_(e, True) Debugging.removeExceptionHandler() del pool
def testAtos(self): NSThread = objc.lookUpClass("NSThread") v = " ".join(hex(x) for x in NSThread.callStackReturnAddresses()) fp = Debugging._run_atos(v) value = fp.read() fp.close() self.assertTrue(any(x in value for x in {"_objc.", "ffi_call_unix64"}))
def develop(): from PyObjCTools import Debugging Debugging.installPythonExceptionHandler() logging.basicConfig(level=logging.INFO) if len(sys.argv) > 1 and sys.argv[1] == 'nose': del sys.argv[1] def run_nose_tests(self, notif): self.controllers['mailboxes'].setView_(self.foldersPane) from tinymail import runtests app = notif.object() cb = runtests.main_o() cb.add(lambda _ign: app.terminate_(self)) TinymailAppDelegate.applicationDidFinishLaunching_ = run_nose_tests
def testAtos(self): NSThread = objc.lookUpClass("NSThread") v = " ".join(hex(x) for x in NSThread.callStackReturnAddresses()) fp = Debugging._run_atos(v) value = fp.read() fp.close() self.assertIn("_objc.", value)
def testInstallExceptionHandler(self): self.assertFalse(Debugging.handlerInstalled()) try: Debugging.installExceptionHandler( verbosity=Debugging.LOGSTACKTRACE, mask=Debugging.EVERYTHINGMASK) self.assertTrue(Debugging.handlerInstalled()) try: cls = objc.lookUpClass("NSException") cls.exceptionWithName_reason_userInfo_("FooBar", "hello world", None).raise__() except Exception as exc: self.assertFalse(Debugging.isPythonException(exc)) else: self.fail("Exception not raised") try: cls = objc.lookUpClass("NSArray") def test(value, idx, stop): raise ValueError("42") a = cls.alloc().initWithArray_([1, 2, 3, 4]) a.indexOfObjectPassingTest_(test) except Exception as exc: self.assertTrue(Debugging.isPythonException(exc)) else: self.fail("Exception not raised") finally: Debugging.removeExceptionHandler() self.assertFalse(Debugging.handlerInstalled())
def runEventLoop( argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain, ): """Run the event loop, ask the user if we should continue if an exception is caught. Use this function instead of NSApplicationMain(). """ if argv is None: argv = sys.argv if pdb is None: pdb = "USE_PDB" in os.environ if pdb: from PyObjCTools import Debugging Debugging.installVerboseExceptionHandler() # bring it to the front, starting from terminal # often won't activator = PyObjCAppHelperApplicationActivator.alloc().init() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( activator, "activateNow:", NSApplicationDidFinishLaunchingNotification, None ) else: Debugging = None if installInterrupt is None and pdb: installInterrupt = True if unexpectedErrorAlert is None: if pdb: unexpectedErrorAlert = unexpectedErrorAlertPdb else: unexpectedErrorAlert = unexpectedErrorAlertPanel runLoop = NSRunLoop.currentRunLoop() stopper = PyObjCAppHelperRunLoopStopper.alloc().init() PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop) firstRun = NSApp() is None try: while stopper.shouldRun(): try: if firstRun: firstRun = False if installInterrupt: installMachInterrupt() main(argv) else: NSApp().run() except RAISETHESE: traceback.print_exc() break except: # noqa: E722, B001 exctype, e, tb = sys.exc_info() if isinstance(e, objc.error): error_str = str(e) NSLog("%@", error_str) elif not unexpectedErrorAlert(): NSLog("%@", "An exception has occured:") traceback.print_exc() sys.exit(0) else: NSLog("%@", "An exception has occured:") traceback.print_exc() else: break finally: if Debugging is not None: Debugging.removeExceptionHandler() PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
def runEventLoop(argv=None, unexpectedErrorAlert=None, installInterrupt=None, pdb=None, main=NSApplicationMain): """Run the event loop, ask the user if we should continue if an exception is caught. Use this function instead of NSApplicationMain(). """ if argv is None: argv = sys.argv if pdb is None: pdb = 'USE_PDB' in os.environ if pdb: from PyObjCTools import Debugging Debugging.installVerboseExceptionHandler() # bring it to the front, starting from terminal # often won't activator = PyObjCAppHelperApplicationActivator.alloc().init() NSNotificationCenter.defaultCenter().addObserver_selector_name_object_( activator, 'activateNow:', NSApplicationDidFinishLaunchingNotification, None, ) else: Debugging = None if installInterrupt is None and pdb: installInterrupt = True if unexpectedErrorAlert is None: if pdb: unexpectedErrorAlert = unexpectedErrorAlertPdb else: unexpectedErrorAlert = unexpectedErrorAlertPanel runLoop = NSRunLoop.currentRunLoop() stopper = PyObjCAppHelperRunLoopStopper.alloc().init() PyObjCAppHelperRunLoopStopper.addRunLoopStopper_toRunLoop_(stopper, runLoop) firstRun = NSApp() is None try: while stopper.shouldRun(): try: if firstRun: firstRun = False if installInterrupt: installMachInterrupt() main(argv) else: NSApp().run() except RAISETHESE: traceback.print_exc() break except: exctype, e, tb = sys.exc_info() objc_exception = False if isinstance(e, objc.error): NSLog("%@", unicode(str(e), 'utf-8', 'replace')) elif not unexpectedErrorAlert(): NSLog("%@", "An exception has occured:") traceback.print_exc() sys.exit(0) else: NSLog("%@", "An exception has occured:") traceback.print_exc() else: break finally: if Debugging is not None: Debugging.removeExceptionHandler() PyObjCAppHelperRunLoopStopper.removeRunLoopStopperFromRunLoop_(runLoop)
#!/usr/bin/env python """ This script shows how to use PyObjCTools.Debugging to show a dump of all (Cocoa) exceptions (handled and unhandled). """ from PyObjCTools import AppHelper from PyObjCTools import Debugging from Foundation import * class FooTester(NSObject): def doCBad_(self, aTimer): NSArray([1])[5] def doBadThingsNow_(self, aTimer): AppHelper.stopEventLoop() raise ValueError("doing bad things") foo = FooTester.alloc().init() NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.5, foo, "doBadThingsNow:", None, False ) NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, foo, "doCBad:", None, False ) # we need to catch everything, because NSTimer handles this one Debugging.installVerboseExceptionHandler() AppHelper.runConsoleEventLoop()
from sdl2 import * #print "importing ctypes" #from ctypes import Structure, sizeof, pointer, c_uint32, c_uint8 import ctypes #print "importing PIL" from PIL import Image #print "everything imported in %.02f seconds" % (time.time() - t) #print #WANTED_FPS = 60. # logitech camera depends on lighting conditions. max 5 fps at night. import PyObjCTools.Debugging as d d.installVerboseExceptionHandler() #d.installPythonExceptionHandler() objc.setVerbose(1) # these are overriden from WebcamVideo object #CAMERA_NAME = "Logitech Camera" # Pro 9000 CAMERA_NAME = "Built-in iSight" CAMERA_NAME = "FaceTime HD Camera" CAMERA_NAME = "Logitech Camera" #WANTED_RESOLUTION = (640, 480) WANTED_RESOLUTION = (320, 240) #WANTED_RESOLUTION = (160, 120) class FpsCounter:
#!/usr/bin/env python """ This script shows how to use PyObjCTools.Debugging to show a dump of all (Cocoa) exceptions (handled and unhandled). """ from PyObjCTools import AppHelper from PyObjCTools import Debugging from Foundation import * class FooTester(NSObject): def doCBad_(self, aTimer): NSArray([1])[5] def doBadThingsNow_(self, aTimer): AppHelper.stopEventLoop() raise ValueError("doing bad things") foo = FooTester.alloc().init() NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.5, foo, 'doBadThingsNow:', None, False ) NSTimer.scheduledTimerWithTimeInterval_target_selector_userInfo_repeats_( 0.0, foo, 'doCBad:', None, False ) # we need to catch everything, because NSTimer handles this one Debugging.installVerboseExceptionHandler() AppHelper.runConsoleEventLoop()
def testHandlerBasic(self): self.assertFalse(Debugging.handlerInstalled()) Debugging.installExceptionHandler() self.assertTrue(Debugging.handlerInstalled()) Debugging.removeExceptionHandler() self.assertFalse(Debugging.handlerInstalled()) Debugging.installVerboseExceptionHandler() self.assertTrue(Debugging.handlerInstalled()) Debugging.removeExceptionHandler() self.assertFalse(Debugging.handlerInstalled()) Debugging.installPythonExceptionHandler() self.assertTrue(Debugging.handlerInstalled()) Debugging.removeExceptionHandler() self.assertFalse(Debugging.handlerInstalled())