Python pdb.runcall() Examples

The following are 23 code examples of pdb.runcall(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pdb , or try the search function .
Example #1
Source File: test_zipimport_support.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_pdb_issue4201(self):
        test_src = textwrap.dedent("""\
                    def f():
                        pass

                    import pdb
                    pdb.runcall(f)
                    """)
        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            p = spawn_python(script_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(script_name, data)
            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            p = spawn_python(zip_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(run_name, data) 
Example #2
Source File: test_zipimport_support.py    From CTFCrackTools with GNU General Public License v3.0 6 votes vote down vote up
def test_pdb_issue4201(self):
        test_src = textwrap.dedent("""\
                    def f():
                        pass

                    import pdb
                    pdb.runcall(f)
                    """)

        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            p = spawn_python(script_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            # Back-port from CPython 3 (see CPython Issue 14255).
            self.assertNormalisedIn(script_name, data)

            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            p = spawn_python(zip_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            # Back-port from CPython 3 (see CPython Issue 14255).
            self.assertNormalisedIn(run_name, data) 
Example #3
Source File: test_zipimport_support.py    From CTFCrackTools-V2 with GNU General Public License v3.0 6 votes vote down vote up
def test_pdb_issue4201(self):
        test_src = textwrap.dedent("""\
                    def f():
                        pass

                    import pdb
                    pdb.runcall(f)
                    """)

        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            p = spawn_python(script_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            # Back-port from CPython 3 (see CPython Issue 14255).
            self.assertNormalisedIn(script_name, data)

            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            p = spawn_python(zip_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            # Back-port from CPython 3 (see CPython Issue 14255).
            self.assertNormalisedIn(run_name, data) 
Example #4
Source File: app.py    From BitTorrent with GNU General Public License v3.0 6 votes vote down vote up
def runReactorWithLogging(config, oldstdout, oldstderr):
    from twisted.internet import reactor
    try:
        if config['profile']:
            if not config['nothotshot']:
                runWithHotshot(reactor, config)
            else:
                runWithProfiler(reactor, config)
        elif config['debug']:
            sys.stdout = oldstdout
            sys.stderr = oldstderr
            if runtime.platformType == 'posix':
                signal.signal(signal.SIGUSR2, lambda *args: pdb.set_trace())
                signal.signal(signal.SIGINT, lambda *args: pdb.set_trace())
            fixPdb()
            pdb.runcall(reactor.run)
        else:
            reactor.run()
    except:
        if config['nodaemon']:
            file = oldstdout
        else:
            file = open("TWISTD-CRASH.log",'a')
        traceback.print_exc(file=file)
        file.flush() 
Example #5
Source File: app.py    From abseil-py with Apache License 2.0 6 votes vote down vote up
def _run_main(main, argv):
  """Calls main, optionally with pdb or profiler."""
  if FLAGS.run_with_pdb:
    sys.exit(pdb.runcall(main, argv))
  elif FLAGS.run_with_profiling or FLAGS.profile_file:
    # Avoid import overhead since most apps (including performance-sensitive
    # ones) won't be run with profiling.
    import atexit
    if FLAGS.use_cprofile_for_profiling:
      import cProfile as profile
    else:
      import profile
    profiler = profile.Profile()
    if FLAGS.profile_file:
      atexit.register(profiler.dump_stats, FLAGS.profile_file)
    else:
      atexit.register(profiler.print_stats)
    retval = profiler.runcall(main, argv)
    sys.exit(retval)
  else:
    sys.exit(main(argv)) 
Example #6
Source File: test_zipimport_support.py    From gcblue with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_pdb_issue4201(self):
        test_src = textwrap.dedent("""\
                    def f():
                        pass

                    import pdb
                    pdb.runcall(f)
                    """)
        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            p = spawn_python(script_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(script_name, data)
            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            p = spawn_python(zip_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(run_name, data) 
Example #7
Source File: app.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def run(self, reactor):
        """
        Run reactor under the cProfile profiler.
        """
        try:
            import cProfile
            import pstats
        except ImportError as e:
            self._reportImportError("cProfile", e)

        p = cProfile.Profile()
        p.runcall(reactor.run)
        if self.saveStats:
            p.dump_stats(self.profileOutput)
        else:
            with open(self.profileOutput, 'w') as stream:
                s = pstats.Stats(p, stream=stream)
                s.strip_dirs()
                s.sort_stats(-1)
                s.print_stats() 
Example #8
Source File: app.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def run(self, reactor):
        """
        Run reactor under the standard profiler.
        """
        try:
            import profile
        except ImportError as e:
            self._reportImportError("profile", e)

        p = profile.Profile()
        p.runcall(reactor.run)
        if self.saveStats:
            p.dump_stats(self.profileOutput)
        else:
            tmp, sys.stdout = sys.stdout, open(self.profileOutput, 'a')
            try:
                p.print_stats()
            finally:
                sys.stdout, tmp = tmp, sys.stdout
                tmp.close() 
Example #9
Source File: debugging.py    From pytest with MIT License 6 votes vote down vote up
def wrap_pytest_function_for_tracing(pyfuncitem):
    """Changes the python function object of the given Function item by a wrapper which actually
    enters pdb before calling the python function itself, effectively leaving the user
    in the pdb prompt in the first statement of the function.
    """
    _pdb = pytestPDB._init_pdb("runcall")
    testfunction = pyfuncitem.obj

    # we can't just return `partial(pdb.runcall, testfunction)` because (on
    # python < 3.7.4) runcall's first param is `func`, which means we'd get
    # an exception if one of the kwargs to testfunction was called `func`
    @functools.wraps(testfunction)
    def wrapper(*args, **kwargs):
        func = functools.partial(testfunction, *args, **kwargs)
        _pdb.runcall(func)

    pyfuncitem.obj = wrapper 
Example #10
Source File: app.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def run(self, reactor):
        """
        Run reactor under the cProfile profiler.
        """
        try:
            import cProfile
            import pstats
        except ImportError as e:
            self._reportImportError("cProfile", e)

        p = cProfile.Profile()
        p.runcall(reactor.run)
        if self.saveStats:
            p.dump_stats(self.profileOutput)
        else:
            with open(self.profileOutput, 'w') as stream:
                s = pstats.Stats(p, stream=stream)
                s.strip_dirs()
                s.sort_stats(-1)
                s.print_stats() 
Example #11
Source File: app.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def run(self, reactor):
        """
        Run reactor under the standard profiler.
        """
        try:
            import profile
        except ImportError as e:
            self._reportImportError("profile", e)

        p = profile.Profile()
        p.runcall(reactor.run)
        if self.saveStats:
            p.dump_stats(self.profileOutput)
        else:
            tmp, sys.stdout = sys.stdout, open(self.profileOutput, 'a')
            try:
                p.print_stats()
            finally:
                sys.stdout, tmp = tmp, sys.stdout
                tmp.close() 
Example #12
Source File: test_zipimport_support.py    From oss-ftp with MIT License 6 votes vote down vote up
def test_pdb_issue4201(self):
        test_src = textwrap.dedent("""\
                    def f():
                        pass

                    import pdb
                    pdb.runcall(f)
                    """)
        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            p = spawn_python(script_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(script_name, data)
            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            p = spawn_python(zip_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(run_name, data) 
Example #13
Source File: test_zipimport_support.py    From BinderFilter with MIT License 6 votes vote down vote up
def test_pdb_issue4201(self):
        test_src = textwrap.dedent("""\
                    def f():
                        pass

                    import pdb
                    pdb.runcall(f)
                    """)
        with temp_dir() as d:
            script_name = make_script(d, 'script', test_src)
            p = spawn_python(script_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(script_name, data)
            zip_name, run_name = make_zip_script(d, "test_zip",
                                                script_name, '__main__.py')
            p = spawn_python(zip_name)
            p.stdin.write('l\n')
            data = kill_python(p)
            self.assertIn(run_name, data) 
Example #14
Source File: __init__.py    From script-languages with MIT License 5 votes vote down vote up
def _run(self):
        with os_timer():
            if self.opts.profiler:
                with tempfile.NamedTemporaryFile() as tmp:
                    cProfile.runctx('self._main()', globals(), locals(), tmp.name)
                    s = pstats.Stats(tmp.name)
                    s.sort_stats("cumulative").print_stats(50)
            elif self.opts.debugger:
                pdb.runcall(self._main)
            elif self.opts.lint:
                self._lint()
            else:
                self._main() 
Example #15
Source File: app.py    From google-apputils with Apache License 2.0 5 votes vote down vote up
def really_start(main=None):
  """Initializes flag values, and calls main with non-flag arguments.

  Only non-flag arguments are passed to main().  The return value of main() is
  used as the exit status.

  Args:
    main: Main function to run with the list of non-flag arguments, or None
      so that sys.modules['__main__'].main is to be used.
  """
  argv = RegisterAndParseFlagsWithUsage()

  if main is None:
    main = sys.modules['__main__'].main

  try:
    if FLAGS.run_with_pdb:
      sys.exit(pdb.runcall(main, argv))
    else:
      if FLAGS.run_with_profiling or FLAGS.profile_file:
        # Avoid import overhead since most apps (including performance-sensitive
        # ones) won't be run with profiling.
        import atexit
        if FLAGS.use_cprofile_for_profiling:
          import cProfile as profile
        else:
          import profile
        profiler = profile.Profile()
        if FLAGS.profile_file:
          atexit.register(profiler.dump_stats, FLAGS.profile_file)
        else:
          atexit.register(profiler.print_stats)
        retval = profiler.runcall(main, argv)
        sys.exit(retval)
      else:
        sys.exit(main(argv))
  except UsageError, error:
    usage(shorthelp=1, detailed_error=error, exitcode=error.exitcode) 
Example #16
Source File: __main__.py    From knmt with GNU General Public License v3.0 5 votes vote down vote up
def run_in_pdb(func, args):
    def debug_signal_handler(signal, frame):
        import pdb
        pdb.set_trace()
    import signal
    signal.signal(signal.SIGINT, debug_signal_handler)

    import pdb as pdb_module

    import sys
    import traceback
    pdb = pdb_module.Pdb()
    while True:
        try:
            pdb.runcall(func, args)
            if pdb._user_requested_quit:
                break
            print("The program finished and will be restarted")
        except pdb_module.Restart:
            print("Restarting with arguments:")
            print("\t" + " ".join(sys.argv[1:]))
        except SystemExit:
            # In most cases SystemExit does not warrant a post-mortem session.
            print("The program exited via sys.exit(). Exit status: ",)
            print(sys.exc_info()[1])
        except SyntaxError:
            traceback.print_exc()
            sys.exit(1)
        except BaseException:
            traceback.print_exc()
            print("Uncaught exception. Entering post mortem debugging")
            print("Running 'cont' or 'step' will restart the program")
            t = sys.exc_info()[2]
            pdb.interaction(None, t)
            print("Post mortem debugger finished. The program will be restarted") 
Example #17
Source File: text_intellisense.py    From Fluid-Designer with GNU General Public License v3.0 4 votes vote down vote up
def execute(self, context):

		binpath = bpy.app.binary_path

		addonspath = binpath[0:binpath.rindex("\\")+1]+str(bpy.app.version[0])+"."+str(bpy.app.version[1])+"\\scripts\\addons\\"

		print(addonspath)

		sc = context.space_data
		text = sc.text

		br = " #breakpoint"

		filepath = addonspath+"debug.py"
		file = open(filepath, "w")
		file.write("import pdb\n")

		for line in text.lines:
			l = line.body

			if line.body.find(br)>-1:
				indent = ""
				for letter in line.body:

					if not letter.isalpha():
						indent+=letter
					else:
						break
				file.write(l[0:-len(br)]+"\n")

				file.write(indent+"pdb.set_trace()\n")

			else:
				file.write(line.body+"\n")



		file.close()

		import pdb
		import debug

		pdb.runcall("debug")


		return {'FINISHED'} 
Example #18
Source File: app.py    From Safejumper-for-Desktop with GNU General Public License v2.0 4 votes vote down vote up
def runReactorWithLogging(config, oldstdout, oldstderr, profiler=None,
                          reactor=None):
    """
    Start the reactor, using profiling if specified by the configuration, and
    log any error happening in the process.

    @param config: configuration of the twistd application.
    @type config: L{ServerOptions}

    @param oldstdout: initial value of C{sys.stdout}.
    @type oldstdout: C{file}

    @param oldstderr: initial value of C{sys.stderr}.
    @type oldstderr: C{file}

    @param profiler: object used to run the reactor with profiling.
    @type profiler: L{AppProfiler}

    @param reactor: The reactor to use.  If L{None}, the global reactor will
        be used.
    """
    if reactor is None:
        from twisted.internet import reactor
    try:
        if config['profile']:
            if profiler is not None:
                profiler.run(reactor)
        elif config['debug']:
            sys.stdout = oldstdout
            sys.stderr = oldstderr
            if runtime.platformType == 'posix':
                signal.signal(signal.SIGUSR2, lambda *args: pdb.set_trace())
                signal.signal(signal.SIGINT, lambda *args: pdb.set_trace())
            fixPdb()
            pdb.runcall(reactor.run)
        else:
            reactor.run()
    except:
        close = False
        if config['nodaemon']:
            file = oldstdout
        else:
            file = open("TWISTD-CRASH.log", "a")
            close = True
        try:
            traceback.print_exc(file=file)
            file.flush()
        finally:
            if close:
                file.close() 
Example #19
Source File: app.py    From learn_python3_spider with MIT License 4 votes vote down vote up
def runReactorWithLogging(config, oldstdout, oldstderr, profiler=None,
                          reactor=None):
    """
    Start the reactor, using profiling if specified by the configuration, and
    log any error happening in the process.

    @param config: configuration of the twistd application.
    @type config: L{ServerOptions}

    @param oldstdout: initial value of C{sys.stdout}.
    @type oldstdout: C{file}

    @param oldstderr: initial value of C{sys.stderr}.
    @type oldstderr: C{file}

    @param profiler: object used to run the reactor with profiling.
    @type profiler: L{AppProfiler}

    @param reactor: The reactor to use.  If L{None}, the global reactor will
        be used.
    """
    if reactor is None:
        from twisted.internet import reactor
    try:
        if config['profile']:
            if profiler is not None:
                profiler.run(reactor)
        elif config['debug']:
            sys.stdout = oldstdout
            sys.stderr = oldstderr
            if runtime.platformType == 'posix':
                signal.signal(signal.SIGUSR2, lambda *args: pdb.set_trace())
                signal.signal(signal.SIGINT, lambda *args: pdb.set_trace())
            fixPdb()
            pdb.runcall(reactor.run)
        else:
            reactor.run()
    except:
        close = False
        if config['nodaemon']:
            file = oldstdout
        else:
            file = open("TWISTD-CRASH.log", "a")
            close = True
        try:
            traceback.print_exc(file=file)
            file.flush()
        finally:
            if close:
                file.close() 
Example #20
Source File: app.py    From python-for-android with Apache License 2.0 4 votes vote down vote up
def runReactorWithLogging(config, oldstdout, oldstderr, profiler=None, reactor=None):
    """
    Start the reactor, using profiling if specified by the configuration, and
    log any error happening in the process.

    @param config: configuration of the twistd application.
    @type config: L{ServerOptions}

    @param oldstdout: initial value of C{sys.stdout}.
    @type oldstdout: C{file}

    @param oldstderr: initial value of C{sys.stderr}.
    @type oldstderr: C{file}

    @param profiler: object used to run the reactor with profiling.
    @type profiler: L{AppProfiler}

    @param reactor: The reactor to use.  If C{None}, the global reactor will
        be used.
    """
    if reactor is None:
        from twisted.internet import reactor
    try:
        if config['profile']:
            if profiler is not None:
                profiler.run(reactor)
        elif config['debug']:
            sys.stdout = oldstdout
            sys.stderr = oldstderr
            if runtime.platformType == 'posix':
                signal.signal(signal.SIGUSR2, lambda *args: pdb.set_trace())
                signal.signal(signal.SIGINT, lambda *args: pdb.set_trace())
            fixPdb()
            pdb.runcall(reactor.run)
        else:
            reactor.run()
    except:
        if config['nodaemon']:
            file = oldstdout
        else:
            file = open("TWISTD-CRASH.log",'a')
        traceback.print_exc(file=file)
        file.flush() 
Example #21
Source File: phase_descriptor.py    From openhtf with Apache License 2.0 4 votes vote down vote up
def __call__(self, test_state):
    """Invoke this Phase, passing in the appropriate args.

    By default, an openhtf.TestApi is passed as the first positional arg, but if
    the 'requires_state' option is set, then a test_state.TestState is passed
    instead. If no positional args are expected, then neither is passed in. In
    any case, keyword args are passed in based on extra_kwargs, set via
    with_args(), combined with plugs (plugs override extra_kwargs).

    Args:
      test_state: test_state.TestState for the currently executing Test.

    Returns:
      The return value from calling the underlying function.
    """
    kwargs = dict(self.extra_kwargs)
    kwargs.update(test_state.plug_manager.provide_plugs(
        (plug.name, plug.cls) for plug in self.plugs if plug.update_kwargs))

    if sys.version_info[0] < 3:
      arg_info = inspect.getargspec(self.func)
      keywords = arg_info.keywords
    else:
      arg_info = inspect.getfullargspec(self.func)
      keywords = arg_info.varkw
    # Pass in test_api if the phase takes *args, or **kwargs with at least 1
    # positional, or more positional args than we have keyword args.
    if arg_info.varargs or (keywords and len(arg_info.args) >= 1) or (
        len(arg_info.args) > len(kwargs)):
      args = []
      if self.options.requires_state:
        args.append(test_state)
      else:
        args.append(test_state.test_api)

      if self.options.run_under_pdb:
        return pdb.runcall(self.func, *args, **kwargs)
      else:
        return self.func(*args, **kwargs)
    if self.options.run_under_pdb:
      return pdb.runcall(self.func, **kwargs)
    else:
      return self.func(**kwargs) 
Example #22
Source File: framework.py    From operator with Apache License 2.0 4 votes vote down vote up
def _reemit(self, single_event_path=None):
        last_event_path = None
        deferred = True
        for event_path, observer_path, method_name in self._storage.notices(single_event_path):
            event_handle = Handle.from_path(event_path)

            if last_event_path != event_path:
                if not deferred and last_event_path is not None:
                    self._storage.drop_snapshot(last_event_path)
                last_event_path = event_path
                deferred = False

            try:
                event = self.load_snapshot(event_handle)
            except NoTypeError:
                self._storage.drop_notice(event_path, observer_path, method_name)
                continue

            event.deferred = False
            observer = self._observer.get(observer_path)
            if observer:
                custom_handler = getattr(observer, method_name, None)
                if custom_handler:
                    event_is_from_juju = isinstance(event, charm.HookEvent)
                    event_is_action = isinstance(event, charm.ActionEvent)
                    if (event_is_from_juju or event_is_action) and 'hook' in self._juju_debug_at:
                        # Present the welcome message and run under PDB.
                        self._show_debug_code_message()
                        pdb.runcall(custom_handler, event)
                    else:
                        # Regular call to the registered method.
                        custom_handler(event)

            if event.deferred:
                deferred = True
            else:
                self._storage.drop_notice(event_path, observer_path, method_name)
            # We intentionally consider this event to be dead and reload it from
            # scratch in the next path.
            self.framework._forget(event)

        if not deferred and last_event_path is not None:
            self._storage.drop_snapshot(last_event_path) 
Example #23
Source File: framework.py    From operator with Apache License 2.0 4 votes vote down vote up
def _reemit(self, single_event_path=None):
        last_event_path = None
        deferred = True
        for event_path, observer_path, method_name in self._storage.notices(single_event_path):
            event_handle = Handle.from_path(event_path)

            if last_event_path != event_path:
                if not deferred and last_event_path is not None:
                    self._storage.drop_snapshot(last_event_path)
                last_event_path = event_path
                deferred = False

            try:
                event = self.load_snapshot(event_handle)
            except NoTypeError:
                self._storage.drop_notice(event_path, observer_path, method_name)
                continue

            event.deferred = False
            observer = self._observer.get(observer_path)
            if observer:
                custom_handler = getattr(observer, method_name, None)
                if custom_handler:
                    event_is_from_juju = isinstance(event, charm.HookEvent)
                    event_is_action = isinstance(event, charm.ActionEvent)
                    if (event_is_from_juju or event_is_action) and 'hook' in self._juju_debug_at:
                        # Present the welcome message and run under PDB.
                        self._show_debug_code_message()
                        pdb.runcall(custom_handler, event)
                    else:
                        # Regular call to the registered method.
                        custom_handler(event)

            if event.deferred:
                deferred = True
            else:
                self._storage.drop_notice(event_path, observer_path, method_name)
            # We intentionally consider this event to be dead and reload it from
            # scratch in the next path.
            self.framework._forget(event)

        if not deferred and last_event_path is not None:
            self._storage.drop_snapshot(last_event_path)