sys._getframe.f_back.f_back

Here are the examples of the python api sys._getframe.f_back.f_back taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

16 Examples 7

Example 1

Project: Limnoria
Source File: dynamicScope.py
View license
    def _getLocals(self, name):
        f = sys._getframe().f_back.f_back # _getLocals <- __[gs]etattr__ <- ...
        while f:
            if name in f.f_locals:
                return f.f_locals
            f = f.f_back
        raise NameError(name)

Example 2

Project: Supybot
Source File: dynamicScope.py
View license
    def _getLocals(self, name):
        f = sys._getframe().f_back.f_back # _getLocals <- __[gs]etattr__ <- ...
        while f:
            if name in f.f_locals:
                return f.f_locals
            f = f.f_back
        raise NameError, name

Example 3

Project: viewfinder
Source File: util.py
View license
  def __init__(self, callback, barrier_type, on_exception=None):
    callback = stack_context.wrap(callback)
    on_exception = stack_context.wrap(on_exception)
    # Parent frame is derived class __init__, so get grandparent frame.
    frame = sys._getframe().f_back.f_back
    self._barrier = _Barrier(callback, on_exception, barrier_type, frame)
    self._stack_context = stack_context.ExceptionStackContext(self._barrier.ReportException)

Example 4

Project: cgstudiomap
Source File: __init__.py
View license
def walk_stack(f):
    """Walk a stack yielding the frame and line number for each frame.

    This will follow f.f_back from the given frame. If no frame is given, the
    current stack is used. Usually used with StackSummary.extract.
    """
    if f is None:
        f = sys._getframe().f_back.f_back
    while f is not None:
        yield f, f.f_lineno
        f = f.f_back

Example 5

Project: EventGhost
Source File: ThreadWorker.py
View license
    def __init__(self, func, args, kwargs, raiseException=True):
        self.time = clock()
        self.func = func
        self.args = args
        self.kwargs = kwargs
        self.returnValue = None
        self.processed = Event()
        self.raiseException = raiseException
        self.exceptionInfo = None
        self.callersFrame = _getframe().f_back.f_back

Example 6

Project: iot-utilities
Source File: traceback.py
View license
def walk_stack(f):
    """Walk a stack yielding the frame and line number for each frame.

    This will follow f.f_back from the given frame. If no frame is given, the
    current stack is used. Usually used with StackSummary.extract.
    """
    if f is None:
        f = sys._getframe().f_back.f_back
    while f is not None:
        yield f, f.f_lineno
        f = f.f_back

Example 7

Project: iot-utilities
Source File: traceback.py
View license
def walk_stack(f):
    """Walk a stack yielding the frame and line number for each frame.

    This will follow f.f_back from the given frame. If no frame is given, the
    current stack is used. Usually used with StackSummary.extract.
    """
    if f is None:
        f = sys._getframe().f_back.f_back
    while f is not None:
        yield f, f.f_lineno
        f = f.f_back

Example 8

Project: iot-utilities
Source File: traceback.py
View license
def walk_stack(f):
    """Walk a stack yielding the frame and line number for each frame.

    This will follow f.f_back from the given frame. If no frame is given, the
    current stack is used. Usually used with StackSummary.extract.
    """
    if f is None:
        f = sys._getframe().f_back.f_back
    while f is not None:
        yield f, f.f_lineno
        f = f.f_back

Example 9

Project: iot-utilities
Source File: traceback.py
View license
def walk_stack(f):
    """Walk a stack yielding the frame and line number for each frame.

    This will follow f.f_back from the given frame. If no frame is given, the
    current stack is used. Usually used with StackSummary.extract.
    """
    if f is None:
        f = sys._getframe().f_back.f_back
    while f is not None:
        yield f, f.f_lineno
        f = f.f_back

Example 10

Project: supybot_fixes
Source File: dynamicScope.py
View license
    def _getLocals(self, name):
        f = sys._getframe().f_back.f_back # _getLocals <- __[gs]etattr__ <- ...
        while f:
            if name in f.f_locals:
                return f.f_locals
            f = f.f_back
        raise NameError, name

Example 11

Project: supybot_fixes
Source File: dynamicScope.py
View license
    def _getLocals(self, name):
        f = sys._getframe().f_back.f_back # _getLocals <- __[gs]etattr__ <- ...
        while f:
            if name in f.f_locals:
                return f.f_locals
            f = f.f_back
        raise NameError, name

Example 12

Project: pudb
Source File: b.py
View license
def set_trace():
    dbg = _get_debugger()
    set_interrupt_handler()
    dbg.set_trace(sys._getframe().f_back.f_back)

Example 13

Project: quickopen
Source File: test_runner.py
View license
def main(parser):
  parser.add_option('--debug', dest='debug', action='store_true', default=False, help='Break into pdb when an assertion fails')
  parser.add_option('-i', '--incremental', dest='incremental', action='store_true', default=False, help='Run tests one at a time.')
  parser.add_option('-s', '--stop', dest='stop_on_error', action='store_true', default=False, help='Stop running tests on error.')
  parser.add_option('-m', '--manually-handled-tests', dest='manual_handling_allowed', action='store_true', default=False, help='Only run tests flagged with a \'requires_manual_handling\' attribute.')
  parser.add_option('--check-for-fd-leaks', dest='check_for_fd_leaks', action='store_true', default=False, help='Checks for fd leaks after each test run.')
  (options, args) = parser.parse_args()

  # install hook on set_trace if --debug
  if options.debug:
    import exceptions
    class DebuggingAssertionError(exceptions.AssertionError):
      def __init__(self, *args):
        exceptions.AssertionError.__init__(self, *args)
        print "Assertion failed, entering PDB..."
        import pdb
        if hasattr(sys, '_getframe'):
          pdb.Pdb().set_trace(sys._getframe().f_back.f_back)
        else:
          pdb.set_trace()
    unittest.TestCase.failureException = DebuggingAssertionError

    def hook(*args):
      import traceback, pdb
      traceback.print_exception(*args)
      pdb.pm()
    sys.excepthook = hook

    try:
      import browser
      browser.debug_mode = True
    except:
      pass

  if options.check_for_fd_leaks and not options.incremental:
    print "--check-for-fd-leaks forces --incremental."
    options.incremental = True

  # make sure cwd is the base directory!
  os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

  def args_filter(test):
    if len(args) == 0:
      return True

    for x in args:
      if str(test).find(x) != -1:
        return True
    return False

  def manual_test_filter(test):
    module_name = test.__class__.__module__
    module = sys.modules[module_name]

    requires_manual_handling = False
    if hasattr(module, 'requires_manual_handling'):
      requires_manual_handling = module.requires_manual_handling
    if requires_manual_handling != options.manual_handling_allowed:
      return False
    return True

  def module_filename_filter(test):
    if test.__class__.__name__.startswith("_"):
      return False

    module_name = test.__class__.__module__
    module = sys.modules[module_name]
    if module.__file__.startswith("."):
      return False
    return True

  def test_filter(test):
    if not module_filename_filter(test):
      return False
    if not manual_test_filter(test):
      return False
    if not args_filter(test):
      return False
    return True

  all_tests_suite = discover("src", "*_test.py", ".")
  selected_tests_suite = filter_suite(all_tests_suite, test_filter)

  if not options.incremental:
    r = unittest.TextTestRunner()
    message_loop.set_unittests_running(True)
    res = r.run(selected_tests_suite)
    message_loop.set_unittests_running(False)
    if res.wasSuccessful():
      return 0
    return 255
  else:
    r = IncrementalTestRunner(options)
    message_loop.set_unittests_running(True)
    ok = True
    for t in get_tests_from_suite(selected_tests_suite):
      assert isinstance(t, unittest.TestCase)
      print '----------------------------------------------------------------------'
      print 'Running %s' % str(t)

      res = r.run(t)
      if not res.wasSuccessful():
        ok = False
        if options.stop_on_error:
          break
    message_loop.set_unittests_running(False)
    if ok:
      return 0
    return 255

Example 14

Project: trace_event_viewer
Source File: test_runner.py
View license
def main(parser):
  parser.add_option('--debug', dest='debug', action='store_true', default=False, help='Break into pdb when an assertion fails')
  parser.add_option('-i', '--incremental', dest='incremental', action='store_true', default=False, help='Run tests one at a time.')
  parser.add_option('-s', '--stop', dest='stop_on_error', action='store_true', default=False, help='Stop running tests on error.')
  (options, args) = parser.parse_args()

  # install hook on set_trace if --debug
  if options.debug:
    import exceptions
    class DebuggingAssertionError(exceptions.AssertionError):
      def __init__(self, *args):
        exceptions.AssertionError.__init__(self, *args)
        print "Assertion failed, entering PDB..."
        import pdb
        if hasattr(sys, '_getframe'):
          pdb.Pdb().set_trace(sys._getframe().f_back.f_back)
        else:
          pdb.set_trace()
    unittest.TestCase.failureException = DebuggingAssertionError

    def hook(*args):
      import traceback, pdb
      traceback.print_exception(*args)
      pdb.pm()
    sys.excepthook = hook

    import browser
    browser.debug_mode = True

  # make sure cwd is the base directory!
  os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

  if len(args) > 0:
    suites = discover(args)
  else:
    suites = discover(['.*'])

  r = unittest.TextTestRunner()
  if not options.incremental:
    res = r.run(suites)
    if res.wasSuccessful():
      return 0
    return 255
  else:
    ok = True
    for s in suites:
      if isinstance(s, unittest.TestSuite):
        for t in s:
          print '----------------------------------------------------------------------'
          print 'Running %s' % str(t)
          res = r.run(t)
          if not res.wasSuccessful():
            ok = False
            if options.stop_on_error:
              break
        if ok == False and options.stop_on_error:
          break
      else:
        res = r.run(s)
        if not res.wasSuccessful():
          ok = False
          if options.stop_on_error:
            break
    if ok:
      return 0
    return 255

Example 15

Project: quickopen
Source File: test_runner.py
View license
def main(parser):
  parser.add_option('--debug', dest='debug', action='store_true', default=False, help='Break into pdb when an assertion fails')
  parser.add_option('-i', '--incremental', dest='incremental', action='store_true', default=False, help='Run tests one at a time.')
  parser.add_option('-s', '--stop', dest='stop_on_error', action='store_true', default=False, help='Stop running tests on error.')
  parser.add_option('-m', '--manually-handled-tests', dest='manual_handling_allowed', action='store_true', default=False, help='Only run tests flagged with a \'requires_manual_handling\' attribute.')
  parser.add_option('--check-for-fd-leaks', dest='check_for_fd_leaks', action='store_true', default=False, help='Checks for fd leaks after each test run.')
  (options, args) = parser.parse_args()

  # install hook on set_trace if --debug
  if options.debug:
    import exceptions
    class DebuggingAssertionError(exceptions.AssertionError):
      def __init__(self, *args):
        exceptions.AssertionError.__init__(self, *args)
        print "Assertion failed, entering PDB..."
        import pdb
        if hasattr(sys, '_getframe'):
          pdb.Pdb().set_trace(sys._getframe().f_back.f_back)
        else:
          pdb.set_trace()
    unittest.TestCase.failureException = DebuggingAssertionError

    def hook(*args):
      import traceback, pdb
      traceback.print_exception(*args)
      pdb.pm()
    sys.excepthook = hook

    try:
      import browser
      browser.debug_mode = True
    except:
      pass

  if options.check_for_fd_leaks and not options.incremental:
    print "--check-for-fd-leaks forces --incremental."
    options.incremental = True

  # make sure cwd is the base directory!
  os.chdir(os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))

  def args_filter(test):
    if len(args) == 0:
      return True

    for x in args:
      if str(test).find(x) != -1:
        return True
    return False

  def manual_test_filter(test):
    module_name = test.__class__.__module__
    module = sys.modules[module_name]

    requires_manual_handling = False
    if hasattr(module, 'requires_manual_handling'):
      requires_manual_handling = module.requires_manual_handling
    if requires_manual_handling != options.manual_handling_allowed:
      return False
    return True

  def module_filename_filter(test):
    if test.__class__.__name__.startswith("_"):
      return False

    module_name = test.__class__.__module__
    module = sys.modules[module_name]
    if module.__file__.startswith("."):
      return False
    return True

  def test_filter(test):
    if not module_filename_filter(test):
      return False
    if not manual_test_filter(test):
      return False
    if not args_filter(test):
      return False
    return True

  all_tests_suite = discover("src", "*_test.py", ".")
  selected_tests_suite = filter_suite(all_tests_suite, test_filter)

  if not options.incremental:
    r = unittest.TextTestRunner()
    message_loop.set_unittests_running(True)
    res = r.run(selected_tests_suite)
    message_loop.set_unittests_running(False)
    if res.wasSuccessful():
      return 0
    return 255
  else:
    r = IncrementalTestRunner(options)
    message_loop.set_unittests_running(True)
    ok = True
    for t in get_tests_from_suite(selected_tests_suite):
      assert isinstance(t, unittest.TestCase)
      print '----------------------------------------------------------------------'
      print 'Running %s' % str(t)

      res = r.run(t)
      if not res.wasSuccessful():
        ok = False
        if options.stop_on_error:
          break
    message_loop.set_unittests_running(False)
    if ok:
      return 0
    return 255

Example 16

Project: sync-engine
Source File: session.py
View license
@contextmanager
def session_scope(id_, versioned=True):
    """
    Provide a transactional scope around a series of operations.

    Takes care of rolling back failed transactions and closing the session
    when it goes out of scope.

    Note that sqlalchemy automatically starts a new database transaction when
    the session is created, and restarts a new transaction after every commit()
    on the session. Your database backend's transaction semantics are important
    here when reasoning about concurrency.

    Parameters
    ----------
    versioned : bool
        Do you want to enable the transaction log?
    debug : bool
        Do you want to turn on SQL echoing? Use with caution. Engine is not
        cached in this case!

    Yields
    ------
    Session
        The created session.

    """
    engine = engine_manager.get_for_id(id_)
    session = new_session(engine, versioned)

    try:
        if config.get('LOG_DB_SESSIONS'):
            start_time = time.time()
            calling_frame = sys._getframe().f_back.f_back
            call_loc = '{}:{}'.format(calling_frame.f_globals.get('__name__'),
                                      calling_frame.f_lineno)
            logger = log.bind(engine_id=id(engine),
                              session_id=id(session), call_loc=call_loc)
            logger.info('creating db_session',
                        sessions_used=engine.pool.checkedout())
        yield session
        session.commit()
    except BaseException as exc:
        try:
            session.rollback()
            raise
        except OperationalError:
            log.warn('Encountered OperationalError on rollback',
                     original_exception=type(exc))
            raise exc
    finally:
        if config.get('LOG_DB_SESSIONS'):
            lifetime = time.time() - start_time
            logger.info('closing db_session', lifetime=lifetime,
                        sessions_used=engine.pool.checkedout())
        session.close()