def run(self): while True: # receive a packet from -j QUEUE if START_DEBUG: rpdb2.start_embedded_debugger(password) (l,msg) = self.s.recv() # discard zero-sized packets if l <= 0: continue pi = iphdr.from_address(addressof(msg.data.payload)) try: link = self.li.num(self.rt.to(int_to_dqn(pi.daddr))[0]["output_link"])["dev"] except: # print "allow packet from %s to %s as a fallback" % (int_to_dqn(pi.saddr),int_to_dqn(pi.daddr)) self.s.verdict(msg.data.packet_id, NF_ACCEPT) qdisc.passed_inc() continue e = ethhdr() e.proto = ETH_P_IP try: e.source = self.ne.to(int_to_dqn(pi.saddr))["raw_lladdr"] except: pass try: e.dest = self.ne.to(int_to_dqn(pi.daddr))["raw_lladdr"] except: pass packet = GenericProtocol(e).inc(msg.data.payload) length = pi.tot_len + sizeof(e) self.queue.put((msg.data.packet_id,link,length,packet))
def deq(self): if START_DEBUG: rpdb2.start_embedded_debugger(password) verdict = NF_DROP # receive a packet from internal queue (packet_id,link,length,packet) = self.queue.get() # filter it for k in self.filters: try: if random() > barrier[k.func_name[2:]][0]: barrier[k.func_name[2:]][1] += 1 (_verdict,packet) = k(self,packet_id,link,length,packet) if _verdict is not None: verdict = _verdict if not packet: self.verdict(packet_id, NF_DROP) return except: pass if link not in self.p_int.keys(): self.p_int[link] = pcap_interface(link) l = self.p_int[link].inject(packet,length) qdisc.injected_inc() if l == -1: self.p_int[link].perror() # print "injected packet from %s to %s" % (int_to_dqn(pi.saddr),int_to_dqn(pi.daddr)) # drop it at OS level self.verdict(packet_id, verdict)
def rpdb2(): """Make a breakpoing using rpdb2 interactive debugger.""" try: import rpdb2 as rpdb2_module if __debug__: try: import pygame pygame.init() pickUpSound = pygame.mixer.Sound( './contrib/_extra/tos-comm.ogg') pickUpSound.play() sleep(2.0) pygame.quit() except Exception: print('For sound notifications about waiting rpdb2(), ' 'please run:\n' 'sudo aptitude install python-pygame') print('rpdb2') rpdb2_module.start_embedded_debugger( version.project_internal_codename.lower(), fAllowRemote=True) except ImportError: raise ImportError(""" For advanced features, please use: sudo aptitude install winpdb """)
def winpdb(depth=0): import rpdb2 depth += 1 if rpdb2.g_debugger is not None: return rpdb2.setbreak(depth) script = rpdb2.calc_frame_path(sys._getframe(depth)) pwd = str(os.getpid()) + os.getcwd().replace('/', '_').replace('-', '_') pid = os.fork() if pid: try: rpdb2.start_embedded_debugger(pwd, depth=depth) finally: os.waitpid(pid, 0) else: try: os.execlp( 'python', 'python', '-c', """import os\nif not os.fork(): import rpdb2, winpdb rpdb2_raw_input = rpdb2._raw_input rpdb2._raw_input = lambda s: \ s == rpdb2.STR_PASSWORD_INPUT and %r or rpdb2_raw_input(s) winpdb.g_ignored_warnings[winpdb.STR_EMBEDDED_WARNING] = True winpdb.main() """ % pwd, '-a', script) finally: os.abort()
def run(self, arglist=None): """Do testing tasks in run""" xenrt.TEC().logverbose("Importing WinPDB libs.") #install rpdb2 to enable WinPDB remote debugging session. #os.system("scp [email protected]:~/debugger_test/rpdb2.py /tmp/") os.system("wget https://winpdb.googlecode.com/hg/rpdb2.py -O /tmp/rpdb2.py") sys.path.append(r"/tmp") import rpdb2 xenrt.TEC().logverbose("Import done. Trying wait remote debugger.") rpdb2.start_embedded_debugger('abc', fAllowRemote = True) log("Hello, world!") log("My host name is %s" % self.host.getName()) a = 10 b = 0 log("print a + b = %d" % a + b); log("print a - b = %d" % a - b); log("print a / b = %d" % a / b); # you can SSH to a guest by doing: ret = self.guest0.execguest("ls") # or to a host by doing: ret = self.host.execdom0("ls")
def logic(self, context): try: call = context[".call"] args = call.pop("args", ()) if context.get("._winpdb_debug", False): password = context.get("._winpdb_password", "password") del context["._winpdb_debug"] del context["._winpdb_password"] try: import rpdb2 except ImportError: context[".console"].text( "rpdb2 is required to debug with WinPDB", fg="red", bold=True ) else: context[".console"].text( "Reading to launch winpdb... Click File -> Attach and enter password '{}'".format( password ), fg="green", bold=True, ) raw_input("Hit <RETURN> to continue ") subprocess.Popen(["winpdb"]) rpdb2.start_embedded_debugger(password) if getattr(self.service, "call_with_context", False): ret = self.service(context, *args, **call) else: ret = self.service(*args, **call) context["_return"] = ReturnContainer(ret) except Exception as e: raise
def set_trace(_rpdb2_pwd='vsi', fAllowUnencrypted=True, fAllowRemote=False, timeout=5*60, source_provider=None, fDebug=False, depth=1): ''' Works, but without the other parts, it's far from auto ''' print 'Starting rpdb2...' rpdb2.start_embedded_debugger(_rpdb2_pwd, fAllowUnencrypted, fAllowRemote, timeout, source_provider, fDebug, depth)
def run(self, arglist=None): """Do testing tasks in run""" xenrt.TEC().logverbose("Importing WinPDB libs.") #install rpdb2 to enable WinPDB remote debugging session. #os.system("scp [email protected]:~/debugger_test/rpdb2.py /tmp/") os.system( "wget https://winpdb.googlecode.com/hg/rpdb2.py -O /tmp/rpdb2.py") sys.path.append(r"/tmp") import rpdb2 xenrt.TEC().logverbose("Import done. Trying wait remote debugger.") rpdb2.start_embedded_debugger('abc', fAllowRemote=True) log("Hello, world!") log("My host name is %s" % self.host.getName()) a = 10 b = 0 log("print a + b = %d" % a + b) log("print a - b = %d" % a - b) log("print a / b = %d" % a / b) # you can SSH to a guest by doing: ret = self.guest0.execguest("ls") # or to a host by doing: ret = self.host.execdom0("ls")
def main(): # configure logging and the Schirm class parser = argparse.ArgumentParser(description="A linux compatible terminal emulator providing modes for rendering (interactive) html documents.") parser.add_argument("-v", "--verbose", help="be verbose, -v for info, -vv for debug log level", action="count") parser.add_argument("--log-filter", help="Only show log messages for this module, e.g. schirm.terminal", nargs="+") parser.add_argument("-d", "--iframe-debug", help="Let iframes use the same domain as the main term frame to be able to access them with javascript from the webkit inspector", action="store_true") parser.add_argument("--no-pty", help="Do not use a pty (pseudo terminal) device.", action="store_true") parser.add_argument("--command", help="The command to execute within the terminal instead of the current users default shell.") parser.add_argument("--rpdb", help="Start the Remote Python debugger using this password.") parser.add_argument("--repl", "--start-clojurescript-repl", help="Start Clojurescript REPL to debug the Schirm client code.", action="store_true") args = parser.parse_args() if args.rpdb: try: import rpdb2 print "run the following command to connect the debugger (password: %r):" % (args.rpdb,) print " rpdb2 --attach %s" % (os.getpid(), ) rpdb2.start_embedded_debugger(args.rpdb) except ImportError: print "install winpdb to debug schirm (`apt-get install winpdb` on ubuntu)" sys.exit(1) init_logger(level=([None, logging.INFO, logging.DEBUG][max(0, min(2, args.verbose))]), filters=args.log_filter) if not (args.verbose and args.verbose > 1): warnings.simplefilter('ignore') run_args = dict run(use_pty=not args.no_pty, cmd=args.command or None, start_clojurescript_repl=args.repl)
def set_trace(self): from rpdb2 import start_embedded_debugger if not self.started: print >> sys.stderr, 'Starting Winpdb server (pid=%d)' % os.getpid( ) start_embedded_debugger(self.password, fAllowRemote=True) self.started = True
def winpdb(depth=0): import rpdb2 depth += 1 if rpdb2.g_debugger is not None: return rpdb2.setbreak(depth) script = rpdb2.calc_frame_path(sys._getframe(depth)) pwd = str(os.getpid()) + os.getcwd().replace('/', '_').replace('-', '_') pid = os.fork() if pid: try: rpdb2.start_embedded_debugger(pwd, depth=depth) finally: os.waitpid(pid, 0) else: try: os.execlp('python', 'python', '-c', """import os\nif not os.fork(): import rpdb2, winpdb rpdb2_raw_input = rpdb2._raw_input rpdb2._raw_input = lambda s: \ s == rpdb2.STR_PASSWORD_INPUT and %r or rpdb2_raw_input(s) winpdb.g_ignored_warnings[winpdb.STR_EMBEDDED_WARNING] = True winpdb.main() """ % pwd, '-a', script) finally: os.abort()
def rpdb(self, *argv, **kwarg): try: import rpdb2 self.log("debug","%s: starting rpdb2" % (self.getName())) rpdb2.start_embedded_debugger(argv[0]) except: self.log("debug","%s: no rpdb2 found, continuing w/o debugging" % (self.getName()))
def rpdb2(): """Make a breakpoing using rpdb2 interactive debugger.""" try: import rpdb2 as rpdb2_module if __debug__: try: import pygame pygame.init() pickUpSound = pygame.mixer.Sound( './contrib/_extra/tos-comm.ogg') pickUpSound.play() sleep(2.0) pygame.quit() except Exception: print('For sound notifications about waiting rpdb2(), ' 'please run:\n' 'sudo aptitude install python-pygame') print('rpdb2') rpdb2_module.start_embedded_debugger(version.project_internal_codename .lower(), fAllowRemote=True) except ImportError: raise ImportError(""" For advanced features, please use: sudo aptitude install winpdb """)
def rpdb2_break(frame, depth): #pylint: disable-msg=W0613 '''Start an embedded debugger session based on WinPDB/RPDB2''' j.logger.log('Starting embedded WinPDB debugger, ' 'this will sleep until you attach your debug ' 'client, or the default timeout (300 seconds) ' 'is reached', 5) # Retrieve configuration config = j.config.getConfig('jumpscale_debugger')['main'] password = config['rpdb2_password'] remote = config['rpdb2_allow_remote'] remote = remote.lower() not in ('0', 'no', 'false', ) kwargs = { 'fAllowRemote': remote, } import inspect # Test whether the installed rpdb2 has 'depth' support, use it if # available. # See http://groups.google.com/group/winpdb/browse_thread/thread/ \ # 7114edb52bbd5be0# if 'depth' in inspect.getargspec(rpdb2.start_embedded_debugger)[0]: kwargs['depth'] = depth + 1 else: j.logger.log('Warning: the debugger will start 2 frames ' 'under the calling frame, you\'ll need to ' 'jump 2 frames up to debug your own code. ' 'A newer version of WinPDB might fix this.', 5) #pylint: disable-msg=W0142 rpdb2.start_embedded_debugger(password, **kwargs)
def run(self): while True: addr = {} message = self.bus.get(addr) # print message if type(message) == types.DictType: if "map" in message.keys(): if message["map"] == "rpdb": try: import rpdb2 self.level["debug"][1]("%s: starting rpdb2" % (self.getName())) rpdb2.start_embedded_debugger(message["argv"][0]) except: self.level["debug"][1]( "%s: no rpdb2 found, continuing w/o debugging" % (self.getName())) elif type(message) == types.StringType: if self.magic(message): return elif type(message) == types.TupleType: s = addr["from"].split("@") if len(s) > 1: system = s[1] else: system = "local" self.level[message[0]][1]("[%s] %s" % (system, message[1]))
def editor_breakpoint(): if not Engine.editor_hint: pass else: print("Awaiting debugger connection") import rpdb2 rpdb2.start_embedded_debugger('notaflex', depth=1)
def breakpoint(): if Engine.editor_hint: print("Skipping breakpoint in editor mode") else: print("Awaiting debugger connection") import rpdb2 rpdb2.start_embedded_debugger('notaflex', depth=1)
def logic(self, context): try: call = context[".call"] args = call.pop("args", ()) if context.get("._winpdb_debug", False): password = context.get("._winpdb_password", "password") del context["._winpdb_debug"] del context["._winpdb_password"] try: import rpdb2 except ImportError: context[".console"].text("rpdb2 is required to debug with WinPDB", fg="red", bold=True) else: context[".console"].text( "Reading to launch winpdb... Click File -> Attach and enter password '{}'".format(password), fg="green", bold=True, ) raw_input("Hit <RETURN> to continue ") subprocess.Popen(["winpdb"]) rpdb2.start_embedded_debugger(password) ret = self.service(*args, **call) context["_return"] = ReturnContainer(ret) except Exception as e: raise
def parse(self, lines): self.state = self.start_state self.tlv_list = [] # import pdb ; pdb.set_trace() if len(sys.argv) > 1 and sys.argv[1] == "rpdb": import rpdb2 rpdb2.start_embedded_debugger('foo', True, True) if isinstance(lines, str): lines = lines.splitlines() for l in lines: if self.state == self.error_state: raise SyntaxError(l) elif self.state == self.end_state: return self.tlv_list elif self.END_TLV_RE.match(l): self.state.end_tlv(l) elif self.TLV_RE.match(l): self.state.tlv(l) elif self.NON_TLV_RE.match(l): self.state.non_tlv(l) elif self.TLV_DATA_RE.match(l): self.state.tlv_data(l) if self.state == self.end_state: return self.tlv_list else: raise SyntaxError("EOF without End of LLDPDU TLV")
def run(self): while True: addr = {} message = self.bus.get(addr) # print message if type(message) == types.DictType: if "map" in message.keys(): if message["map"] == "rpdb": try: import rpdb2 self.level["debug"][1]("%s: starting rpdb2" % (self.getName())) rpdb2.start_embedded_debugger(message["argv"][0]) except: self.level["debug"][1]("%s: no rpdb2 found, continuing w/o debugging" % (self.getName())) elif type(message) == types.StringType: if self.magic(message): return elif type(message) == types.TupleType: s = addr["from"].split("@") if len(s) > 1: system = s[1] else: system = "local" self.level[message[0]][1]("[%s] %s" % (system, message[1]))
def sigusr_handler(sig, frame): try: import rpdb2 rpdb2.start_embedded_debugger('password') except: log.exception( "SIGUSR1 caught but embedded debugger could not be started")
def set_trace(_rpdb2_pwd='vsi', fAllowUnencrypted=True, fAllowRemote=False, timeout=5 * 60, source_provider=None, fDebug=False, depth=1): ''' Works, but without the other parts, it's far from auto Parameters ---------- _rpdb2_pwd : str The Remote Python Debugger Password fAllowUnencrypted : bool True if unencrypted is allowed. False if not. fAllowRemote : bool True if a remote is allowed. False if not. Default: False timeout : int The timeout period in seconds. source_provider : str The Source Provider fDebug : bool The Debug Output depth : int The Depth of the frame. Default: 0 ''' print('Starting rpdb2...') rpdb2.start_embedded_debugger(_rpdb2_pwd, fAllowUnencrypted, fAllowRemote, timeout, source_provider, fDebug, depth)
def _debug(signal_number, interrupted_frame): import sys sys.stderr.write( "** %s received, entering debugger\n" "** Type 'c' to continue or 'q' to stop the process\n" "** Or %s again to quit (and possibly dump core)\n" % (_breakin_signal_name, _breakin_signal_name) ) # It seems that on Windows, when sys.stderr is to a PIPE, then we need to # flush. Not sure why it is buffered, but that seems to be the case. sys.stderr.flush() # restore default meaning so that you can kill the process by hitting it # twice signal.signal(_breakin_signal_number, signal.SIG_DFL) try: try: import rpdb2 rpdb2.start_embedded_debugger("breakin") except ImportError: import pdb pdb.set_trace() finally: signal.signal(_breakin_signal_number, _debug)
def startDebugger(mode='SCIPION_DEBUG', password='******'): if mode != 'SCIPION_DEBUG' or envVarOn('SCIPION_DEBUG'): try: from rpdb2 import start_embedded_debugger start_embedded_debugger(password) except Exception: print "Error importing rpdb2 debugging module, consider installing winpdb."
def run_debugger(args): module_file = sys.modules[__name__].__file__ if args.debug: log.msg( "Waiting for debugger connection. Please attach a debugger, e.g.:", system='db') log.msg("winpdb --attach %s" % (module_file), system='db') import rpdb2 rpdb2.start_embedded_debugger(args.debug) if args.winpdb: rid = random.randint(1, 100000) pw = ''.join( random.choice(string.ascii_uppercase + string.digits) for x in xrange(8)) with closing( open( os.path.expanduser('~/.rpdb2_settings/passwords/%s' % rid), 'w')) as f: f.write(pw) log.msg("Spawning winpdb", system='db') subprocess.Popen( ['winpdb', '--rid', str(rid), '--attach', module_file]) log.msg("Waiting for debugger connection", system='db') import rpdb2 rpdb2.start_embedded_debugger(pw)
def startDebugger(mode='SCIPION_DEBUG', password='******'): if mode != 'SCIPION_DEBUG' or envVarOn('SCIPION_DEBUG'): try: from rpdb2 import start_embedded_debugger print "Starting debugger..." start_embedded_debugger(password) except Exception: print "Error importing rpdb2 debugging module, consider installing winpdb."
def some_func(x, y): try: return x / y except: print "Wait for debugger..." rpdb2.start_embedded_debugger("my_passwd") raise
def setBreakPoint(): global _RD_PWD global _TIME_OUT if os.environ['RD_RUN_MODE'] == 'DEBUG': import rpdb2 rpdb2.start_embedded_debugger(_rpdb2_pwd=_RD_PWD, fAllowRemote=True, timeout=_TIME_OUT)
def rpdb(self, *argv, **kwarg): try: import rpdb2 self.log("debug", "%s: starting rpdb2" % (self.getName())) rpdb2.start_embedded_debugger(argv[0]) except: self.log( "debug", "%s: no rpdb2 found, continuing w/o debugging" % (self.getName()))
def remotedebug(): # see: http://code.google.com/p/winpdb/ try: import rpdb2 p = os.popen('echo debug | winpdb -a pypedebug.py', 'w') rpdb2.start_embedded_debugger('debug') p.close() except ImportError: pass
def start_debugging(self, config=None): started = False try: import rpdb2 rpdb2.start_embedded_debugger('qgis', timeout=10.0) started = True except: pass return started
def launch_debugger(): if not settings.WinPDB.ACTIVE: return __xbmcgui__.Dialog().notification(__addonid__, "Debugger on, waiting for connection ({}s)...").format(settings.WinPDB.TIMEOUT) import rpdb2 rpdb2.start_embedded_debugger('pw', timeout=settings.WinPDB.TIMEOUT)
def winpdb_break(): ''' Breakpoint for winpdb debugger. Example: from syr import winpdb_break; winpdb_break() #DEBUG ''' import rpdb2 #DEBUG log('breakpointing for winpdb') rpdb2.start_embedded_debugger("password") #DEBUG
def winpdb_break(): ''' Breakpoint for winpdb debugger. Example: from denova.python.utils import winpdb_break; winpdb_break() #DEBUG ''' import rpdb2 #DEBUG log('breakpointing for winpdb') rpdb2.start_embedded_debugger("password") #DEBUG
def debug_handler(_, frame): if log_stack: log.info("Got SIGUSR2. Traceback:\n%s", ''.join(traceback.format_stack(frame))) if start_debugger_password: try: import rpdb2 rpdb2.start_embedded_debugger(start_debugger_password) except ImportError: log.error('rpdb2, part of winpdb, is required to start debugger. Please install package: pip install winpdb')
def startWindPDBClient(self): started = False try: import rpdb2 rpdb2.start_embedded_debugger('qgis', timeout=10.0) started = True self._statusBar().showMessage(u"WinPDB debugging active") except: pass return started
def startDebugger(password='******'): if Config.debugOn(): try: # FIXME: rpdb2 does not support python 3 from rpdb2 import start_embedded_debugger print("Starting debugger...") start_embedded_debugger(password) except Exception: print( "Error importing rpdb2 debugging module, consider installing winpdb." )
def debug_handler(_, frame): if log_stack: log.info("Got SIGUSR2. Traceback:\n%s", ''.join(traceback.format_stack(frame))) if start_debugger_password: try: import rpdb2 rpdb2.start_embedded_debugger(start_debugger_password) except ImportError: log.error( 'rpdb2, part of winpdb, is required to start debugger. Please install package: pip install winpdb' )
def deferred_startup(): debug.log.debug('Loading deferred') from pygui.deferred_startup import init_startup init_startup() try: file('/tmp/ready', 'w') except: pass if os.environ.get('RPDB') or 'rpdb' in config.plugins: import rpdb2 rpdb2.start_embedded_debugger('pygui', fAllowRemote=True, timeout=60) import socket socket.setdefaulttimeout(config.socket_timeout)
def setup_debugging(): logger.debug('Instantiating embedded rpdb2 debugger with password "bff"...') try: import rpdb2 rpdb2.start_embedded_debugger("bff", timeout=5.0) except ImportError: logger.debug('Skipping import of rpdb2. Is Winpdb installed?') logger.debug('Enabling heapy remote monitoring...') try: from guppy import hpy # @UnusedImport import guppy.heapy.RM # @UnusedImport except ImportError: logger.debug('Skipping import of heapy. Is Guppy-PE installed?')
def wdb_f(self, arg): """ Debug a script (like %run -d) in IPython process, Using WinPdb Usage: %wdb test.py run test.py, with a winpdb breakpoint at start of the file %wdb pass Change the password (e.g. if you have forgotten the old one) Note that after the script has been run, you need to do "Go" (f5) in WinPdb to resume normal IPython operation. """ global rpdb_started if not arg.strip(): print __doc__ return if arg.strip() == 'pass': passwd = raw_input('Enter new winpdb session password: '******'winpdb_pass'] = passwd print "Winpdb password changed" if rpdb_started: print "You need to restart IPython to use the new password" return path = os.path.abspath(arg) if not os.path.isfile(path): raise UsageError("%%wdb: file %s does not exist" % path) if not rpdb_started: passwd = ip.db.get('winpdb_pass', None) if passwd is None: import textwrap print textwrap.dedent("""\ Winpdb sessions need a password that you use for attaching the external winpdb session. IPython will remember this. You can change the password later by '%wpdb pass' """) passwd = raw_input('Enter new winpdb session password: '******'winpdb_pass'] = passwd print "Starting rpdb2 in IPython process" rpdb2.start_embedded_debugger(passwd, timeout=0) rpdb_started = True rpdb2.set_temp_breakpoint(path) print 'It is time to attach with WinPdb (launch WinPdb if needed, File -> Attach)' ip.magic('%run ' + arg)
def wdb_f(self, arg): """ Debug a script (like %run -d) in IPython process, Using WinPdb Usage: %wdb test.py run test.py, with a winpdb breakpoint at start of the file %wdb pass Change the password (e.g. if you have forgotten the old one) Note that after the script has been run, you need to do "Go" (f5) in WinPdb to resume normal IPython operation. """ global rpdb_started if not arg.strip(): print __doc__ return if arg.strip() == 'pass': passwd = raw_input('Enter new winpdb session password: '******'winpdb_pass'] = passwd print "Winpdb password changed" if rpdb_started: print "You need to restart IPython to use the new password" return path = os.path.abspath(arg) if not os.path.isfile(path): raise IPython.ipapi.UsageError("%%wdb: file %s does not exist" % path) if not rpdb_started: passwd = ip.db.get('winpdb_pass', None) if passwd is None: import textwrap print textwrap.dedent("""\ Winpdb sessions need a password that you use for attaching the external winpdb session. IPython will remember this. You can change the password later by '%wpdb pass' """) passwd = raw_input('Enter new winpdb session password: '******'winpdb_pass'] = passwd print "Starting rpdb2 in IPython process" rpdb2.start_embedded_debugger(passwd, timeout = 0) rpdb_started = True rpdb2.set_temp_breakpoint(path) print 'It is time to attach with WinPdb (launch WinPdb if needed, File -> Attach)' ip.magic('%run ' + arg)
def debug(what): # # We will form the argument list for Winpdb invocation: # # # Argument 1: Python executable name. # (We cannot utilize here os.executable, because it returns "Blender.exe", # instead "python.exe)" # if os.name in ("nt", "mac"): args = ["pythonw"] # On Windows and Mac use this else: args = ["python"] #On Linux and other systems - standard python # # Argument 2: full path to Winpdb.py script name # args.append(os.path.join(os.path.dirname(rpdb2_file), "winpdb.py")) # # Argument 3: -a(ttach) specified script # args.append("-a") # # Argument 4: -p(assword): it is only available on nt systems. # if os.name == "nt": args.append("-p" + PASSWORD) # # Argument 5: name of the debugged script # args.append(what) # # Finally: run WinPdb... # if os.name == "nt": pid = subprocess.Popen(args) else: # # On Linux systems: we have to pass the password with stdin! # pid = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) pid.stdin.write(PASSWORD + "\n") pid.stdin.flush() # # ....and let it to connect, waiting for <timeout> seconds: # start_embedded_debugger(PASSWORD, timeout=WAIT_TIMEOUT)
def start(*args, **kargs): global g_debugging, g_debug_session_ready python = get_python_interpreter() log("START (g_debugging: %s)" % g_debugging) # todo wrap at exit, such that end of winpdb without detaching does not make # plugin host stop and st2 exit rpdb2 = import_rpdb2() if g_debugging: if g_winpdb is None: winpdb = debug_session(python, shutdown_at_exit=False) rpdb2.g_thread_start_new_thread(debug_session_monitor, (winpdb, )) time.sleep(0.1) rpdb2.setbreak(depth=1) return #rpdb2.g_thread_start_new_thread(debug_session, tuple(python, False)) time.sleep(0.1) # initialize debugger (there is a thread starting, so we have to wait for it) rpdb2.start_embedded_debugger("sublime", timeout=0, source_provider=SublimeTextSourceProvider()) log("wait for debug server") # wait for running debugger thread wait_for_debug_server() if g_winpdb is None: winpdb = debug_session(python, shutdown_at_exit=False) rpdb2.g_thread_start_new_thread(debug_session_monitor, (winpdb, )) #g_debug_session_ready = False #while not g_debug_session_ready: #time.sleep(0.1) log("break") rpdb2.setbreak(depth=1) g_debugging = True
def break_here(restrict_machine=None): if ((not restrict_machine) or (restrict_machine in server_names)): # The parent process ID seems to be one for the route daemon... # 2014.05.08: Not working again for route daemon, getting pdb instead. use_pdb = not_apache_parent and (os.getppid() != 1) g.log.warning('===============================================') g.log.warning(' WAITING ON %s PYTHON DEBUGGER...' % ('LOCAL' if use_pdb else 'LOCAL', )) g.log.warning('===============================================') if use_pdb: import pdb pdb.set_trace() else: import rpdb2 rpdb2.start_embedded_debugger('password', fAllowRemote=True)
def startRemoteDebugger(self, err): """ Launch the rpdb2 session. """ import rpdb2 stdout = sys.stdout sys.stdout = sys.__stdout__ sys.stdout.write( 'You have %d seconds to connect to the remote debugger using ' '"%s" password.' % (self.timeout, self.password)) try: rpdb2.start_embedded_debugger( self.password, timeout=self.timeout, fAllowRemote=True) finally: sys.stdout = stdout
def do_debug(): """Run blogofile in debug mode depending on the BLOGOFILE_DEBUG environment variable: If set to "ipython" just start up an embeddable ipython shell at bf.ipshell If set to anything else besides 0, setup winpdb environment """ try: if os.environ['BLOGOFILE_DEBUG'] == "ipython": from IPython.Shell import IPShellEmbed bf.ipshell = IPShellEmbed() elif os.environ['BLOGOFILE_DEBUG'] != "0": print("Running in debug mode, waiting for debugger to connect. " "Password is set to 'blogofile'") import rpdb2 rpdb2.start_embedded_debugger("blogofile") except KeyError: pass #Not running in debug mode
def debug(what): # # We will form the argument list for Winpdb invocation: # # # Argument 1: Python executable name. # (We cannot utilize here os.executable, because it returns "Blender.exe", # instead "python.exe)" # if os.name in ("nt","mac"): args=["pythonw"] # On Windows and Mac use this else: args = ["python"] #On Linux and other systems - standard python # # Argument 2: full path to Winpdb.py script name # args.append(os.path.join(os.path.dirname(rpdb2_file),"winpdb.py")) # # Argument 3: -a(ttach) specified script # args.append("-a") # # Argument 4: -p(assword): it is only available on nt systems. # if os.name == "nt": args.append("-p" + PASSWORD) # # Argument 5: name of the debugged script # args.append(what) # # Finally: run WinPdb... # if os.name == "nt": pid = subprocess.Popen(args) else: # # On Linux systems: we have to pass the password with stdin! # pid = subprocess.Popen(args, stdin = subprocess.PIPE, stdout = subprocess.PIPE) pid.stdin.write(PASSWORD + "\n") pid.stdin.flush() # # ....and let it to connect, waiting for <timeout> seconds: # start_embedded_debugger(PASSWORD, timeout = WAIT_TIMEOUT)
def assurt(condit, message=None, soft=False): if not bool(condit): # FIXME: This doesn't work if being run as a service. Can you figure out # if we're a daemon and throw a normal assert instead? if debug_me: log.warning('DEBUGGING!!') print 'DEBUGGING!!' if iamwhoiam: import pdb; pdb.set_trace() else: log.warning('Waiting for remote debug client...') print 'Waiting for remote debug client...' import rpdb2 rpdb2.start_embedded_debugger('password', fAllowRemote=True) assrt = Ccp_Assert(message) if not soft: raise assrt else: log.error('Soft Assert: %s' % (str(assrt),))
def run_cli(arguments): """Command line execution entry point for running tests. :param arguments: Command line arguments as a list of strings. For programmatic usage the :func:`run` function is typically better. It has a better API for that usage and does not call :func:`sys.exit` like this function. Example:: from robot import run_cli run_cli(['--include', 'tag', 'path/to/tests.html']) """ if '--debug' in arguments: import rpdb2 rpdb2.start_embedded_debugger(arguments.index('--debug') + 1) RobotFramework().execute_cli(arguments)
def new_command(s): """ New command from the debugging socket """ notifier.socket_remove(s, 0) cmd = s.recv(struct.unpack('!I', s.recv(4))[0]).strip().split(' ') if cmd[0] == 'trace': global socket_trace if socket_trace: socket_trace_close() socket_trace = s print '=== START TRACE ===' sys.settrace(socket_trace_send) if cmd[0] == 'winpdb': s.send('ok\n') s.close() socket_trace_close() print '=== START WINPDB EMBEDDED DEBUGGER ===' import rpdb2; rpdb2.start_embedded_debugger('kaa')
def run_debugger(args): module_file = sys.modules[__name__].__file__ if args.debug: log.msg("Waiting for debugger connection. Please attach a debugger, e.g.:", system='db') log.msg("winpdb --attach %s" % (module_file), system='db') import rpdb2 rpdb2.start_embedded_debugger(args.debug) if args.winpdb: rid = random.randint(1, 100000) pw = ''.join(random.choice(string.ascii_uppercase + string.digits) for x in xrange(8)) with closing(open(os.path.expanduser('~/.rpdb2_settings/passwords/%s' % rid), 'w')) as f: f.write(pw) log.msg("Spawning winpdb", system='db') subprocess.Popen(['winpdb', '--rid', str(rid), '--attach', module_file]) log.msg("Waiting for debugger connection", system='db') import rpdb2 rpdb2.start_embedded_debugger(pw)
def signal_hook(sig, frame): """ Hooks into a SIGUSR1 signal from the os to allow an interactive debugger at a certain point. :param sig: the signal we sent in. should be signal.SIGUSR1 :type sig: signal.SIGUSR1 :param frame: The current frame of execution """ d={'_frame':frame} # Allow access to frame object. d.update(frame.f_globals) # Unless shadowed by global d.update(frame.f_locals) try: import rpdb2; rpdb2.start_embedded_debugger('UNIFIED!!!') except: i = code.InteractiveConsole(d) message = "Signal received : entering python shell.\nTraceback:\n" message += ''.join(traceback.format_stack(frame)) i.interact(message)