Exemple #1
0
def main():
    """Wdb entry point"""
    sys.path.insert(0, os.getcwd())
    args, extrargs = parser.parse_known_args()
    sys.argv = ['wdb'] + extrargs

    if args.file:
        file = os.path.join(os.getcwd(), args.file)
        if args.source:
            print('The source argument cannot be used with file.')
            sys.exit(1)

        if not os.path.exists(file):
            print('Error:', file, 'does not exist')
            sys.exit(1)

        Wdb.get().run_file(file)
    else:
        source = None
        if args.source:
            source = os.path.join(os.getcwd(), args.source)
            if not os.path.exists(source):
                print('Error:', source, 'does not exist')
                sys.exit(1)

        Wdb.get().shell(source)
Exemple #2
0
async def run_file(file_name: str) -> None:  # pragma: no cover
    """
    Function for run file debug
    """
    # pylint: disable=import-outside-toplevel
    from wdb import Wdb  # isort:skip

    Wdb.get().run_file(file_name)
Exemple #3
0
async def run_shell() -> None:  # pragma: no cover
    """
    Function for run shell(debug)
    """
    # pylint: disable=import-outside-toplevel
    from wdb import Wdb  # isort:skip

    Wdb.get().shell()
Exemple #4
0
def main():
    """Inspired by python -m pdb. Debug any python script with wdb"""
    if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
        print("usage: wdb.py scriptfile [arg] ...")
        sys.exit(2)

    mainpyfile = sys.argv[1]
    if not os.path.exists(mainpyfile):
        print('Error:', mainpyfile, 'does not exist')
        sys.exit(1)

    del sys.argv[0]
    sys.path[0] = os.path.dirname(mainpyfile)

    Wdb.get().run_file(mainpyfile)
Exemple #5
0
def main():
    """Inspired by python -m pdb. Debug any python script with wdb"""
    if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
        print("usage: wdb.py scriptfile [arg] ...")
        sys.exit(2)

    mainpyfile = sys.argv[1]
    if not os.path.exists(mainpyfile):
        print('Error:', mainpyfile, 'does not exist')
        sys.exit(1)

    del sys.argv[0]
    sys.path[0] = os.path.dirname(mainpyfile)

    Wdb.get().run_file(mainpyfile)
Exemple #6
0
    def init_new_wdbr(frame, event, args):
        """First settrace call start the debugger for the current thread"""
        import threading
        import sys
        from wdb import Wdb
        thread = threading.currentThread()
        if getattr(thread, 'no_trace', False):
            sys.settrace(None)
            return

        wdbr_thread = Wdb.make_server()
        thread._wdbr = wdbr_thread

        frame = sys._getframe().f_back
        wdbr_thread.stopframe = frame
        wdbr_thread.botframe = frame

        while frame:
            frame.f_trace = wdbr_thread.trace_dispatch
            frame = frame.f_back
        wdbr_thread.stoplineno = -1

        def trace(frame, event, arg):
            rv = wdbr_thread.trace_dispatch(frame, event, arg)
            fn = frame.f_code.co_filename
            if (rv is None and not
                (fn == os.path.abspath(fn) or fn.startswith('<')) and not
                fn.startswith(
                    os.path.dirname(os.path.abspath(sys.argv[0])))):
                return
            return trace

        sys.settrace(trace)
        return wdbr_thread.trace_dispatch
Exemple #7
0
    def init_new_wdbr(frame, event, args):
        """First settrace call start the debugger for the current thread"""
        import threading
        import sys
        from wdb import Wdb
        thread = threading.currentThread()
        if getattr(thread, 'no_trace', False):
            sys.settrace(None)
            return

        wdbr_thread = Wdb.make_server()
        thread._wdbr = wdbr_thread

        frame = sys._getframe().f_back
        wdbr_thread.stopframe = frame
        wdbr_thread.botframe = frame

        while frame:
            frame.f_trace = wdbr_thread.trace_dispatch
            frame = frame.f_back
        wdbr_thread.stoplineno = -1

        def trace(frame, event, arg):
            rv = wdbr_thread.trace_dispatch(frame, event, arg)
            fn = frame.f_code.co_filename
            if (rv is None
                    and not (fn == os.path.abspath(fn) or fn.startswith('<'))
                    and not fn.startswith(
                        os.path.dirname(os.path.abspath(sys.argv[0])))):
                return
            return trace

        sys.settrace(trace)
        return wdbr_thread.trace_dispatch
Exemple #8
0
    def tracing_fork():
        import sys
        import multiprocessing
        from wdb import Wdb
        pid = osfork()

        if pid == 0:
            # Doesn't work with Wdb.trace()...
            sys.settrace(None)
            wdbr_process = Wdb.make_server()

            def trace(frame, event, arg):
                process = multiprocessing.current_process()
                if not hasattr(process, '_wdbr'):
                    process._wdbr = wdbr_process
                rv = wdbr_process.trace_dispatch(frame, event, arg)
                fn = frame.f_code.co_filename
                if (rv is None and
                    (fn == os.path.abspath(fn) or fn.startswith('<')) and not
                    fn.startswith(
                        os.path.dirname(os.path.abspath(sys.argv[0])))):
                    return
                return trace

            frame = sys._getframe().f_back
            wdbr_process.stoplineno = -1
            wdbr_process.stopframe = frame
            while frame:
                frame.f_trace = wdbr_process.trace_dispatch
                wdbr_process.botframe = frame
                frame = frame.f_back
            sys.settrace(trace)

        return pid
Exemple #9
0
    def _wdb_execute(*args, **kwargs):
        from wdb import trace, Wdb

        if Wdb.enabled:
            wdb = Wdb.get()
            wdb.closed = False  # Activate request ignores

        interesting = True
        if len(args) > 0 and isinstance(args[0], ErrorHandler):
            interesting = False
        elif (len(args) > 2 and isinstance(args[0], StaticFileHandler)
              and args[2] == 'favicon.ico'):
            interesting = False

        if Wdb.enabled and interesting:
            with trace(close_on_exit=True, under=under):
                old_execute(*args, **kwargs)
        else:
            old_execute(*args, **kwargs)
            # Close set_trace debuggers
            stop_trace(close_on_exit=True)

        if Wdb.enabled:
            # Reset closed state
            wdb.closed = False
Exemple #10
0
    def tracing_fork():
        import sys
        import multiprocessing
        from wdb import Wdb
        pid = osfork()

        if pid == 0:
            # Doesn't work with Wdb.trace()...
            sys.settrace(None)
            wdbr_process = Wdb.make_server()

            def trace(frame, event, arg):
                process = multiprocessing.current_process()
                if not hasattr(process, '_wdbr'):
                    process._wdbr = wdbr_process
                rv = wdbr_process.trace_dispatch(frame, event, arg)
                fn = frame.f_code.co_filename
                if (rv is None
                        and (fn == os.path.abspath(fn) or fn.startswith('<'))
                        and not fn.startswith(
                            os.path.dirname(os.path.abspath(sys.argv[0])))):
                    return
                return trace

            frame = sys._getframe().f_back
            wdbr_process.stoplineno = -1
            wdbr_process.stopframe = frame
            while frame:
                frame.f_trace = wdbr_process.trace_dispatch
                wdbr_process.botframe = frame
                frame = frame.f_back
            sys.settrace(trace)

        return pid
Exemple #11
0
def run():
    init()
    app.wsgi_app = Wdb(app.wsgi_app)
    app.run(debug=True,
            host='0.0.0.0',
            port=1984,
            use_debugger=False,
            use_reloader=True,
            threaded=True)
Exemple #12
0
 def f():
     # Enable wdb
     wdb = Wdb.get()
     Wdb.enabled = True
     start_response('200 OK', [('Content-Type', 'text/html'),
                               ('X-Thing', wdb.uuid)])
     yield to_bytes(' ' * 4096)
     wdb = set_trace()
     wdb.die()
     yield to_bytes('Exited')
Exemple #13
0
 def f():
     # Enable wdb
     wdb = Wdb.get()
     Wdb.enabled = True
     start_response('200 OK', [
         ('Content-Type', 'text/html'), ('X-Thing', wdb.uuid)])
     yield to_bytes(' ' * 4096)
     wdb = set_trace()
     wdb.die()
     yield to_bytes('Exited')
Exemple #14
0
def main():
    """Wdb entry point"""
    sys.path.insert(0, os.getcwd())
    args, extrargs = parser.parse_known_args()
    sys.argv = ['wdb'] + args.args + extrargs

    if args.file:
        file = os.path.join(os.getcwd(), args.file)
        if args.source:
            print('The source argument cannot be used with file.')
            sys.exit(1)

        if not os.path.exists(file):
            print('Error:', file, 'does not exist')
            sys.exit(1)
        if args.trace:
            Wdb.get().run_file(file)
        else:

            def wdb_pm(xtype, value, traceback):
                sys.__excepthook__(xtype, value, traceback)
                wdb = Wdb.get()
                wdb.reset()
                wdb.interaction(None, traceback, post_mortem=True)

            sys.excepthook = wdb_pm

            with open(file) as f:
                code = compile(f.read(), file, 'exec')
                execute(code, globals(), globals())

    else:
        source = None
        if args.source:
            source = os.path.join(os.getcwd(), args.source)
            if not os.path.exists(source):
                print('Error:', source, 'does not exist')
                sys.exit(1)

        Wdb.get().shell(source)
Exemple #15
0
def main():
    """Wdb entry point"""
    sys.path.insert(0, os.getcwd())
    args, extrargs = parser.parse_known_args()
    sys.argv = ['wdb'] + args.args + extrargs

    if args.file:
        file = os.path.join(os.getcwd(), args.file)
        if args.source:
            print('The source argument cannot be used with file.')
            sys.exit(1)

        if not os.path.exists(file):
            print('Error:', file, 'does not exist')
            sys.exit(1)
        if args.trace:
            Wdb.get().run_file(file)
        else:

            def wdb_pm(xtype, value, traceback):
                sys.__excepthook__(xtype, value, traceback)
                wdb = Wdb.get()
                wdb.reset()
                wdb.interaction(None, traceback, post_mortem=True)

            sys.excepthook = wdb_pm

            with open(file) as f:
                code = compile(f.read(), file, 'exec')
                execute(code, globals(), globals())

    else:
        source = None
        if args.source:
            source = os.path.join(os.getcwd(), args.source)
            if not os.path.exists(source):
                print('Error:', source, 'does not exist')
                sys.exit(1)

        Wdb.get().shell(source)
Exemple #16
0
 def trace_wsgi(environ, start_response):
     wdb = Wdb.get()
     wdb.closed = False
     appiter = None
     try:
         with trace(close_on_exit=True, under=self.app):
             appiter = self.app(environ, start_response)
             for item in appiter:
                 yield item
     except Exception:
         start_response('500 INTERNAL SERVER ERROR', [
             ('Content-Type', 'text/html')])
         yield _handle_off()
     finally:
         hasattr(appiter, 'close') and appiter.close()
     wdb.closed = False
Exemple #17
0
 def trace_wsgi(environ, start_response):
     wdb = Wdb.get()
     wdb.closed = False
     appiter = None
     try:
         with trace(close_on_exit=True, under=self.app):
             appiter = self.app(environ, start_response)
             for item in appiter:
                 yield item
     except Exception:
         start_response('500 INTERNAL SERVER ERROR',
                        [('Content-Type', 'text/html')])
         yield _handle_off()
     finally:
         hasattr(appiter, 'close') and appiter.close()
     wdb.closed = False
Exemple #18
0
 def catch(environ, start_response):
     wdb = Wdb.get()
     wdb.closed = False
     appiter = None
     try:
         appiter = self.app(environ, start_response)
         for item in appiter:
             yield item
     except Exception:
         start_response('500 INTERNAL SERVER ERROR', [
             ('Content-Type', 'text/html')])
         yield _handle_off()
     finally:
         # Close set_trace debuggers
         stop_trace(close_on_exit=True)
         hasattr(appiter, 'close') and appiter.close()
     wdb.closed = False
Exemple #19
0
 def catch(environ, start_response):
     wdb = Wdb.get()
     wdb.closed = False
     appiter = None
     try:
         appiter = self.app(environ, start_response)
         for item in appiter:
             yield item
     except Exception:
         start_response('500 INTERNAL SERVER ERROR',
                        [('Content-Type', 'text/html')])
         yield _handle_off()
     finally:
         # Close set_trace debuggers
         stop_trace(close_on_exit=True)
         hasattr(appiter, 'close') and appiter.close()
     wdb.closed = False
Exemple #20
0
    def _wdb_execute(*args, **kwargs):
        from wdb import trace, Wdb
        wdb = Wdb.get()
        wdb.closed = False  # Activate request ignores

        interesting = True
        if len(args) > 0 and isinstance(args[0], ErrorHandler):
            interesting = False
        elif len(args) > 2 and isinstance(
                args[0], StaticFileHandler) and args[2] == 'favicon.ico':
            interesting = False

        if Wdb.enabled and interesting:
            with trace(close_on_exit=True, under=under):
                old_execute(*args, **kwargs)
        else:
            old_execute(*args, **kwargs)
            # Close set_trace debuggers
            stop_trace(close_on_exit=True)

        # Reset closed state
        wdb.closed = False
Exemple #21
0
def post_mortem_interaction(uuid, exc_info):
    wdb = Wdb.get(force_uuid=uuid)
    type_, value, tb = exc_info
    frame = None
    _value = value
    if not isinstance(_value, BaseException):
        _value = type_(value)

    wdb.obj_cache[id(exc_info)] = exc_info
    wdb.extra_vars['__exception__'] = exc_info
    exception = type_.__name__
    exception_description = str(value) + ' [POST MORTEM]'
    init = 'Echo|%s' % dump(
        {
            'for': '__exception__',
            'val': escape('%s: %s') % (exception, exception_description)
        })

    wdb.interaction(frame,
                    tb,
                    exception,
                    exception_description,
                    init=init,
                    iframe_mode=True)
Exemple #22
0
 def wdb_pm(xtype, value, traceback):
     sys.__excepthook__(xtype, value, traceback)
     wdb = Wdb.get()
     wdb.reset()
     wdb.interaction(None, traceback, post_mortem=True)
Exemple #23
0
def main():
    """Inspired by python -m pdb. Debug any python script with wdb"""
    if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
        print("usage: wdb.py scriptfile [arg] ...")
        sys.exit(2)

    mainpyfile = sys.argv[1]
    if not os.path.exists(mainpyfile):
        print('Error:', mainpyfile, 'does not exist')
        sys.exit(1)

    del sys.argv[0]
    sys.path[0] = os.path.dirname(mainpyfile)

    # Let's make a server in case of
    wdbr = Wdb.trace()

    # Multithread support
    # Monkey patch threading to have callback to kill thread debugger
    old_thread_start = threading.Thread.start

    def wdb_thread_start(self):
        """Monkey patched start monkey patching run"""
        self.old_run = self.run

        def run(self):
            """Monkey patched run"""
            try:
                self.old_run()
            finally:
                if hasattr(self, '_wdbr'):
                    self._wdbr.die()

        from wdb._compat import bind
        self.run = bind(self, run)
        old_thread_start(self)

    threading.Thread.start = wdb_thread_start

    def init_new_wdbr(frame, event, args):
        """First settrace call start the debugger for the current thread"""
        import threading
        import sys
        from wdb import Wdb
        thread = threading.currentThread()
        if getattr(thread, 'no_trace', False):
            sys.settrace(None)
            return

        wdbr_thread = Wdb.make_server()
        thread._wdbr = wdbr_thread

        frame = sys._getframe().f_back
        wdbr_thread.stopframe = frame
        wdbr_thread.botframe = frame

        while frame:
            frame.f_trace = wdbr_thread.trace_dispatch
            frame = frame.f_back
        wdbr_thread.stoplineno = -1

        def trace(frame, event, arg):
            rv = wdbr_thread.trace_dispatch(frame, event, arg)
            fn = frame.f_code.co_filename
            if (rv is None
                    and not (fn == os.path.abspath(fn) or fn.startswith('<'))
                    and not fn.startswith(
                        os.path.dirname(os.path.abspath(sys.argv[0])))):
                return
            return trace

        sys.settrace(trace)
        return wdbr_thread.trace_dispatch

    threading.settrace(init_new_wdbr)

    # Multiprocess support
    # Monkey patch threading to have callback to kill thread debugger
    old_process_start = multiprocessing.Process.start

    def wdb_process_start(self):
        """Monkey patched start monkey patching run"""
        self.old_run = self.run

        def run(self):
            """Monkey patched run"""
            try:
                self.old_run()
            finally:
                if hasattr(self, '_wdbr'):
                    self._wdbr.die()

        from wdb._compat import bind
        self.run = bind(self, run)
        old_process_start(self)

    multiprocessing.Process.start = wdb_process_start

    # Monkey patching fork
    osfork = os.fork

    def tracing_fork():
        import sys
        import multiprocessing
        from wdb import Wdb
        pid = osfork()

        if pid == 0:
            # Doesn't work with Wdb.trace()...
            sys.settrace(None)
            wdbr_process = Wdb.make_server()

            def trace(frame, event, arg):
                process = multiprocessing.current_process()
                if not hasattr(process, '_wdbr'):
                    process._wdbr = wdbr_process
                rv = wdbr_process.trace_dispatch(frame, event, arg)
                fn = frame.f_code.co_filename
                if (rv is None
                        and (fn == os.path.abspath(fn) or fn.startswith('<'))
                        and not fn.startswith(
                            os.path.dirname(os.path.abspath(sys.argv[0])))):
                    return
                return trace

            frame = sys._getframe().f_back
            wdbr_process.stoplineno = -1
            wdbr_process.stopframe = frame
            while frame:
                frame.f_trace = wdbr_process.trace_dispatch
                wdbr_process.botframe = frame
                frame = frame.f_back
            sys.settrace(trace)

        return pid

    if os.fork != tracing_fork:
        os._original_fork = osfork
        os.fork = tracing_fork

    try:
        Wdb.run_file(mainpyfile)
    finally:
        wdbr.quitting = True
        wdbr.stop_trace(True)
Exemple #24
0
 def run():
     from wdb import Wdb
     Wdb.get().run_file(fn)
Exemple #25
0
 def run():
     from wdb import Wdb
     Wdb.get().run_file(fn[0].decode('utf-8'))
Exemple #26
0
 def run():
     from wdb import Wdb
     Wdb.get().run_file(fn)
Exemple #27
0
 def run():
     from wdb import Wdb
     Wdb.get().shell()
Exemple #28
0
 def wdb_pm(xtype, value, traceback):
     sys.__excepthook__(xtype, value, traceback)
     wdb = Wdb.get()
     wdb.reset()
     wdb.interaction(None, traceback, post_mortem=True)
Exemple #29
0
app.logger.addHandler(handler)
import werkzeug
werkzeug._internal._log('debug', '<-- I am with stupid')
logging.getLogger('werkzeug').handlers = []
logging.getLogger('werkzeug').addHandler(handler)
handler.setLevel(getattr(logging, 'DEBUG'))
app.logger.setLevel(getattr(logging, 'DEBUG'))
logging.getLogger('werkzeug').setLevel(getattr(logging, 'DEBUG'))

try:
    import wsreload
except ImportError:
    app.logger.debug('wsreload not found')
else:
    url = "http://l:1984/*"

    def log(httpserver):
        app.logger.debug('WSReloaded after server restart')

    wsreload.monkey_patch_http_server({'url': url}, callback=log)
    app.logger.debug('HTTPServer monkey patched for url %s' % url)

app.wsgi_app = Wdb(app.wsgi_app)
app.run(debug=True,
        host='0.0.0.0',
        port=1984,
        use_debugger=False,
        use_reloader=True,
        threaded=False)
# 80chars 80chars 80chars 80chars 80chars 80chars 80chars 80chars 80chars 80char
Exemple #30
0
def main():
    """Inspired by python -m pdb. Debug any python script with wdb"""
    if not sys.argv[1:] or sys.argv[1] in ("--help", "-h"):
        print("usage: wdb.py scriptfile [arg] ...")
        sys.exit(2)

    mainpyfile = sys.argv[1]
    if not os.path.exists(mainpyfile):
        print('Error:', mainpyfile, 'does not exist')
        sys.exit(1)

    del sys.argv[0]
    sys.path[0] = os.path.dirname(mainpyfile)

    # Let's make a server in case of
    wdbr = Wdb.trace()

    # Multithread support
    # Monkey patch threading to have callback to kill thread debugger
    old_thread_start = threading.Thread.start

    def wdb_thread_start(self):
        """Monkey patched start monkey patching run"""
        self.old_run = self.run

        def run(self):
            """Monkey patched run"""
            try:
                self.old_run()
            finally:
                if hasattr(self, '_wdbr'):
                    self._wdbr.die()

        from wdb._compat import bind
        self.run = bind(self, run)
        old_thread_start(self)
    threading.Thread.start = wdb_thread_start

    def init_new_wdbr(frame, event, args):
        """First settrace call start the debugger for the current thread"""
        import threading
        import sys
        from wdb import Wdb
        thread = threading.currentThread()
        if getattr(thread, 'no_trace', False):
            sys.settrace(None)
            return

        wdbr_thread = Wdb.make_server()
        thread._wdbr = wdbr_thread

        frame = sys._getframe().f_back
        wdbr_thread.stopframe = frame
        wdbr_thread.botframe = frame

        while frame:
            frame.f_trace = wdbr_thread.trace_dispatch
            frame = frame.f_back
        wdbr_thread.stoplineno = -1

        def trace(frame, event, arg):
            rv = wdbr_thread.trace_dispatch(frame, event, arg)
            fn = frame.f_code.co_filename
            if (rv is None and not
                (fn == os.path.abspath(fn) or fn.startswith('<')) and not
                fn.startswith(
                    os.path.dirname(os.path.abspath(sys.argv[0])))):
                return
            return trace

        sys.settrace(trace)
        return wdbr_thread.trace_dispatch

    threading.settrace(init_new_wdbr)

    # Multiprocess support
    # Monkey patch threading to have callback to kill thread debugger
    old_process_start = multiprocessing.Process.start

    def wdb_process_start(self):
        """Monkey patched start monkey patching run"""
        self.old_run = self.run

        def run(self):
            """Monkey patched run"""
            try:
                self.old_run()
            finally:
                if hasattr(self, '_wdbr'):
                    self._wdbr.die()
        from wdb._compat import bind
        self.run = bind(self, run)
        old_process_start(self)
    multiprocessing.Process.start = wdb_process_start

    # Monkey patching fork
    osfork = os.fork

    def tracing_fork():
        import sys
        import multiprocessing
        from wdb import Wdb
        pid = osfork()

        if pid == 0:
            # Doesn't work with Wdb.trace()...
            sys.settrace(None)
            wdbr_process = Wdb.make_server()

            def trace(frame, event, arg):
                process = multiprocessing.current_process()
                if not hasattr(process, '_wdbr'):
                    process._wdbr = wdbr_process
                rv = wdbr_process.trace_dispatch(frame, event, arg)
                fn = frame.f_code.co_filename
                if (rv is None and
                    (fn == os.path.abspath(fn) or fn.startswith('<')) and not
                    fn.startswith(
                        os.path.dirname(os.path.abspath(sys.argv[0])))):
                    return
                return trace

            frame = sys._getframe().f_back
            wdbr_process.stoplineno = -1
            wdbr_process.stopframe = frame
            while frame:
                frame.f_trace = wdbr_process.trace_dispatch
                wdbr_process.botframe = frame
                frame = frame.f_back
            sys.settrace(trace)

        return pid

    if os.fork != tracing_fork:
        os._original_fork = osfork
        os.fork = tracing_fork

    try:
        Wdb.run_file(mainpyfile)
    finally:
        wdbr.quitting = True
        wdbr.stop_trace(True)
Exemple #31
0
 def run():
     from wdb import Wdb
     Wdb.get().shell()