def run_main_loop():
  global _old_std
  _old_std = [ sys.stdout, sys.stderr ]

  if DEBUG:
    tempStdout = open('/tmp/quickopen.stdout', 'w', 0)
    sys.stdout = tempStdout
    sys.stderr = sys.stdout
  else:
    tempStdout = cStringIO.StringIO()
    sys.stdout = tempStdout
    sys.stderr = sys.stdout

  assert not is_main_loop_running()
  if _unittests_running and not _active_test:
    del _pending_delayed_tasks[:]
    del _quit_handlers[:]
    raise Exception("UITestCase must be used for tests that use the message_loop.")

  global _main_loop_running
  global _stdscr
  global _quitting

  def main(stdscr):
    global _stdscr
    _stdscr = stdscr
    while _main_loop_running:
      now = time.time()
      if len(_pending_delayed_tasks) > 0:
        delay = max(0, _pending_delayed_tasks[0].run_at_or_after - now)
      else:
        delay = 0.1
      try:
        r, w, e = select.select([sys.stdin], [], [], delay)
      except __HOLE__:
        raise
      except:
        continue

      if not _main_loop_running:
        break
      if r:
        if on_terminal_readable.has_listeners:
          on_terminal_readable.fire()
        else:
          print "unhandled character:", _stdscr.getch()
      _run_pending_tasks()
  try:
    _main_loop_running = True
    curses.wrapper(main)
  except KeyboardInterrupt:
    traceback.print_exc()
    raise
  except:
    traceback.print_exc()
  finally:
    _stdscr = None
    _quitting = False
    _main_loop_running = False
    del _pending_delayed_tasks[:]
    sys.stdout = _old_std[0]
    sys.stderr = _old_std[1]
    if DEBUG:
      tempStdout.close()
      res = open('/tmp/quickopen.stdout')
      sys.stdout.write(res.read())
      res.close()
    else:
      sys.stdout.write(tempStdout.getvalue())
dataset/ETHPy150Open natduca/quickopen/src/message_loop_curses.py/run_main_loop