INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Return True if we are looking at a class definition statement
def is_class_def(line, frame): """Return True if we are looking at a class definition statement""" return (line and _re_class.match(line) and stmt_contains_opcode(frame.f_code, frame.f_lineno, 'BUILD_CLASS'))
quit command when there s just one thread.
def nothread_quit(self, arg): """ quit command when there's just one thread. """ self.debugger.core.stop() self.debugger.core.execution_status = 'Quit command' raise Mexcept.DebuggerQuit
quit command when several threads are involved.
def threaded_quit(self, arg): """ quit command when several threads are involved. """ threading_list = threading.enumerate() mythread = threading.currentThread() for t in threading_list: if t != mythread: ctype_async_raise(t, Mexcept.DebuggerQuit) ...
Get bacground from default values based on the TERM environment variable
def set_default_bg(): """Get bacground from default values based on the TERM environment variable """ term = environ.get('TERM', None) if term: if (term.startswith('xterm',) or term.startswith('eterm') or term == 'dtterm'): return False return True
Pass as parameters R G B values in hex On return variable is_dark_bg is set
def is_dark_rgb(r, g, b): """Pass as parameters R G B values in hex On return, variable is_dark_bg is set """ try: midpoint = int(environ.get('TERMINAL_COLOR_MIDPOINT', None)) except: pass if not midpoint: term = environ.get('TERM', None) # 117963 = (* .6 (+ 6553...
Consult ( environment ) variables DARK_BG and COLORFGB On return variable is_dark_bg is set
def is_dark_color_fg_bg(): """Consult (environment) variables DARK_BG and COLORFGB On return, variable is_dark_bg is set""" dark_bg = environ.get('DARK_BG', None) if dark_bg is not None: return dark_bg != '0' color_fg_bg = environ.get('COLORFGBG', None) if color_fg_bg: if color_f...
Handle debugger options. Set option_list if you are writing another main program and want to extend the existing set of debugger options.
def process_options(debugger_name, pkg_version, sys_argv, option_list=None): """Handle debugger options. Set `option_list' if you are writing another main program and want to extend the existing set of debugger options. The options dicionary from opt_parser is return. sys_argv is also updated.""" ...
Handle options ( opts ) that feed into the debugger ( dbg )
def _postprocess_options(dbg, opts): ''' Handle options (`opts') that feed into the debugger (`dbg')''' # Set dbg.settings['printset'] print_events = [] if opts.fntrace: print_events = ['c_call', 'c_return', 'call', 'return'] # if opts.linetrace: print_events += ['line'] if len(print_events): ...
Routine which gets run if we were invoked directly
def main(dbg=None, sys_argv=list(sys.argv)): """Routine which gets run if we were invoked directly""" global __title__ # Save the original just for use in the restart that works via exec. orig_sys_argv = list(sys_argv) opts, dbg_opts, sys_argv = process_options(__title__, __version__, ...
Get the name caller s caller. NB: f_code. co_filenames and thus this code kind of broken for zip ed eggs circa Jan 2009
def get_name(): """Get the name caller's caller. NB: f_code.co_filenames and thus this code kind of broken for zip'ed eggs circa Jan 2009 """ caller = sys._getframe(2) filename = caller.f_code.co_filename filename = os.path.normcase(os.path.basename(filename)) return os.path.splitext(fil...
return suitable frame signature to key display expressions off of.
def signature(frame): '''return suitable frame signature to key display expressions off of.''' if not frame: return None code = frame.f_code return (code.co_name, code.co_filename, code.co_firstlineno)
List all display items ; return 0 if none
def all(self): """List all display items; return 0 if none""" found = False s = [] for display in self.list: if not found: s.append("""Auto-display expressions now in effect: Num Enb Expression""") found = True pass ...
Delete display expression * display_number *
def delete_index(self, display_number): """Delete display expression *display_number*""" old_size = len(self.list) self.list = [disp for disp in self.list if display_number != disp.number] return old_size != len(self.list)
display any items that are active
def display(self, frame): '''display any items that are active''' if not frame: return s = [] sig = signature(frame) for display in self.list: if display.signature == sig and display.enabled: s.append(display.to_s(frame)) pass ...
format display item
def format(self, show_enabled=True): '''format display item''' what = '' if show_enabled: if self.enabled: what += ' y ' else: what += ' n ' pass pass if self.fmt: what += self.fmt + ' ' ...
Read one message unit. It s possible however that more than one message will be set in a receive so we will have to buffer that for the next read. EOFError will be raised on EOF.
def read_msg(self): """Read one message unit. It's possible however that more than one message will be set in a receive, so we will have to buffer that for the next read. EOFError will be raised on EOF. """ if self.state == 'connected': if 0 == len(self.buf): ...
Return the current debugger instance ( if any ) or creates a new one.
def debugger(): """Return the current debugger instance (if any), or creates a new one.""" dbg = _current[0] if dbg is None or not dbg.active: dbg = _current[0] = RemoteCeleryTrepan() return dbg
Set breakpoint at current location or a specified frame
def debug(frame=None): """Set breakpoint at current location, or a specified frame""" # ??? if frame is None: frame = _frame().f_back dbg = RemoteCeleryTrepan() dbg.say(BANNER.format(self=dbg)) # dbg.say(SESSION_STARTED.format(self=dbg)) trepan.api.debug(dbg_opts=dbg.dbg_opts)
Given the path to a. py file return the path to its. pyc/. pyo file.
def cache_from_source(path, debug_override=None): """Given the path to a .py file, return the path to its .pyc/.pyo file. The .py file does not need to exist; this simply returns the path to the .pyc/.pyo file calculated as if the .py file were imported. The extension will be .pyc unless sys.flags.opt...
Create an instance of each of the debugger subcommands. Commands are found by importing files in the directory name + sub. Some files are excluded via an array set in __init__. For each of the remaining files we import them and scan for class names inside those files and for each class name we will create an instance o...
def _load_debugger_subcommands(self, name): """ Create an instance of each of the debugger subcommands. Commands are found by importing files in the directory 'name' + 'sub'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them an...
Give help for a command which has subcommands. This can be called in several ways: help cmd help cmd subcmd help cmd commands
def help(self, args): """Give help for a command which has subcommands. This can be called in several ways: help cmd help cmd subcmd help cmd commands Our shtick is to give help for the overall command only if subcommand or 'commands' is not given. If...
Ooops -- the debugger author didn t redefine this run docstring.
def run(self, args): """Ooops -- the debugger author didn't redefine this run docstring.""" if len(args) < 2: # We were given cmd without a subcommand; cmd is something # like "show", "info" or "set". Generally this means list # all of the subcommands. sel...
Error message when subcommand asked for but doesn t exist
def undefined_subcmd(self, cmd, subcmd): """Error message when subcommand asked for but doesn't exist""" self.proc.intf[-1].errmsg(('Undefined "%s" subcommand: "%s". ' + 'Try "help %s *".') % (cmd, subcmd, cmd)) return
Execute a code object.
def runcode(obj, code_obj): """Execute a code object. When an exception occurs, self.showtraceback() is called to display a traceback. All exceptions are caught except SystemExit, which is reraised. A note about KeyboardInterrupt: this exception may occur elsewhere in this code, and may not a...
** down ** [ * count * ]
def run(self, args): """**down** [*count*] Move the current frame down in the stack trace (to a newer frame). 0 is the most recent frame. If no count is given, move down 1. See also: --------- `up` and `frame`.""" Mframe.adjust_relative(self.proc, self.name, args, self.signum) return False
Expand fields in Location namedtuple. If:.: get fields from stack function/ module: get fields from evaluation/ introspection location file and line number: use that
def resolve_location(proc, location): """Expand fields in Location namedtuple. If: '.': get fields from stack function/module: get fields from evaluation/introspection location file and line number: use that """ curframe = proc.curframe if location == '.': if not curframe: ...
Expand fields in Location namedtuple. If:.: get fields from stack function/ module: get fields from evaluation/ introspection location file and line number: use that
def resolve_address_location(proc, location): """Expand fields in Location namedtuple. If: '.': get fields from stack function/module: get fields from evaluation/introspection location file and line number: use that """ curframe = proc.curframe if location == '.': filename ...
The dance we have to do to set debugger frame state to * frame * which is in the thread with id * thread_id *. We may need to the hide initial debugger frames.
def find_and_set_debugged_frame(self, frame, thread_id): '''The dance we have to do to set debugger frame state to *frame*, which is in the thread with id *thread_id*. We may need to the hide initial debugger frames. ''' thread = threading._active[thread_id] thread_name =...
The simple case: thread frame switching has been done or is not needed and we have an explicit position number as a string
def one_arg_run(self, position_str): '''The simple case: thread frame switching has been done or is not needed and we have an explicit position number as a string''' frame_num = self.proc.get_an_int(position_str, ("The 'frame' command requires a" + ...
See if * name_or_id * is either a thread name or a thread id. The frame of that id/ name is returned or None if name_or_id is invalid.
def get_from_thread_name_or_id(self, name_or_id, report_error=True): '''See if *name_or_id* is either a thread name or a thread id. The frame of that id/name is returned, or None if name_or_id is invalid.''' thread_id = self.proc.get_int_noerr(name_or_id) if thread_id is None: ...
Run a frame command. This routine is a little complex because we allow a number parameter variations.
def run(self, args): '''Run a frame command. This routine is a little complex because we allow a number parameter variations.''' if len(args) == 1: # Form is: "frame" which means "frame 0" position_str = '0' elif len(args) == 2: # Form is: "frame {pos...
Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not.
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''): '''Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not. ''' if type(val) != list: return False numeric = True for i in range(len(val)): if not (type(val[...
Routine which gets run if we were invoked directly
def main(dbg=None, sys_argv=list(sys.argv)): """Routine which gets run if we were invoked directly""" global __title__ # Save the original just for use in the restart that works via exec. orig_sys_argv = list(sys_argv) opts, dbg_opts, sys_argv = Moptions.process_options(__title__, ...
Use this to set where to write to. output can be a file object or a string. This code raises IOError on error.
def open(self, output, opts=None): """Use this to set where to write to. output can be a file object or a string. This code raises IOError on error.""" if isinstance(output, io.TextIOWrapper) or \ isinstance(output, io.StringIO) or \ output == sys.stdout: pass ...
This method the debugger uses to write. In contrast to writeline no newline is added to the end to str.
def write(self, msg): """ This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'. """ if self.output.closed: raise IOError("writing %s on a closed file" % msg) self.output.write(msg) if self.flush_after_write:...
Find the corresponding signal name for num. Return None if num is invalid.
def lookup_signame(num): """Find the corresponding signal name for 'num'. Return None if 'num' is invalid.""" signames = signal.__dict__ num = abs(num) for signame in list(signames.keys()): if signame.startswith('SIG') and signames[signame] == num: return signame pass ...
Find the corresponding signal number for name. Return None if name is invalid.
def lookup_signum(name): """Find the corresponding signal number for 'name'. Return None if 'name' is invalid.""" uname = name.upper() if (uname.startswith('SIG') and hasattr(signal, uname)): return getattr(signal, uname) else: uname = "SIG"+uname if hasattr(signal, uname): ...
Return a signal name for a signal name or signal number. Return None is name_num is an int but not a valid signal number and False if name_num is a not number. If name_num is a signal name or signal number the canonic if name is returned.
def canonic_signame(name_num): """Return a signal name for a signal name or signal number. Return None is name_num is an int but not a valid signal number and False if name_num is a not number. If name_num is a signal name or signal number, the canonic if name is returned.""" signum = lookup_signum...
A replacement for signal. signal which chains the signal behind the debugger s handler
def set_signal_replacement(self, signum, handle): """A replacement for signal.signal which chains the signal behind the debugger's handler""" signame = lookup_signame(signum) if signame is None: self.dbgr.intf[-1].errmsg(("%s is not a signal number" ...
Check to see if a single signal handler that we are interested in has changed or has not been set initially. On return self. sigs [ signame ] should have our signal handler. True is returned if the same or adjusted False or None if error or not found.
def check_and_adjust_sighandler(self, signame, sigs): """ Check to see if a single signal handler that we are interested in has changed or has not been set initially. On return self.sigs[signame] should have our signal handler. True is returned if the same or adjusted, False or N...
Check to see if any of the signal handlers we are interested in have changed or is not initially set. Change any that are not right.
def check_and_adjust_sighandlers(self): """Check to see if any of the signal handlers we are interested in have changed or is not initially set. Change any that are not right. """ for signame in list(self.sigs.keys()): if not self.check_and_adjust_sighandler(signame, self.sigs): ...
Print status for a single signal name ( signame )
def print_info_signal_entry(self, signame): """Print status for a single signal name (signame)""" if signame in signal_description: description=signal_description[signame] else: description="" pass if signame not in list(self.sigs.keys()): ...
Print information about a signal
def info_signal(self, args): """Print information about a signal""" if len(args) == 0: return None signame = args[0] if signame in ['handle', 'signal']: # This has come from dbgr's info command if len(args) == 1: # Show all signal handlers ...
Delegate the actions specified in arg to another method.
def action(self, arg): """Delegate the actions specified in 'arg' to another method. """ if not arg: self.info_signal(['handle']) return True args = arg.split() signame = args[0] signame = self.is_name_or_number(args[0]) if not sign...
Set whether we stop or not when this signal is caught. If set_stop is True your program will stop when this signal happens.
def handle_print_stack(self, signame, print_stack): """Set whether we stop or not when this signal is caught. If 'set_stop' is True your program will stop when this signal happens.""" self.sigs[signame].print_stack = print_stack return print_stack
Set whether we stop or not when this signal is caught. If set_stop is True your program will stop when this signal happens.
def handle_stop(self, signame, set_stop): """Set whether we stop or not when this signal is caught. If 'set_stop' is True your program will stop when this signal happens.""" if set_stop: self.sigs[signame].b_stop = True # stop keyword implies print AND nopas...
Set whether we pass this signal to the program ( or not ) when this signal is caught. If set_pass is True Dbgr should allow your program to see this signal.
def handle_pass(self, signame, set_pass): """Set whether we pass this signal to the program (or not) when this signal is caught. If set_pass is True, Dbgr should allow your program to see this signal. """ self.sigs[signame].pass_along = set_pass if set_pass: #...
Set whether we print or not when this signal is caught.
def handle_print(self, signame, set_print): """Set whether we print or not when this signal is caught.""" if set_print: self.sigs[signame].print_method = self.dbgr.intf[-1].msg else: self.sigs[signame].print_method = None pass return set_print
This method is called when a signal is received.
def handle(self, signum, frame): """This method is called when a signal is received.""" if self.print_method: self.print_method('\nProgram received signal %s.' % self.signame) if self.print_stack: import traceback strings = traceb...
Check whether specified line seems to be executable.
def is_ok_line_for_breakpoint(filename, lineno, errmsg_fn): """Check whether specified line seems to be executable. Return `lineno` if it is, 0 if not (e.g. a docstring, comment, blank line or EOF). Warning: testing is not comprehensive. """ line = linecache.getline(filename, lineno) if not lin...
Given a file name extract the most likely module name.
def file2module(filename): """Given a file name, extract the most likely module name. """ basename = osp.basename(filename) if '.' in basename: pos = basename.rfind('.') return basename[:pos] else: return basename return None
Return a full pathname for filename if we can find one. path is a list of directories to prepend to filename. If no file is found we ll return None
def search_file(filename, directories, cdir): """Return a full pathname for filename if we can find one. path is a list of directories to prepend to filename. If no file is found we'll return None""" for trydir in directories: # Handle $cwd and $cdir if trydir =='$cwd': trydir='.' ...
Do a shell - like path lookup for py_script and return the results. If we can t find anything return py_script
def whence_file(py_script, dirnames=None): """Do a shell-like path lookup for py_script and return the results. If we can't find anything return py_script""" if py_script.find(os.sep) != -1: # Don't search since this name has path separator components return py_script if dirnames is None...
Return a string representation of an object
def print_obj(arg, frame, format=None, short=False): """Return a string representation of an object """ try: if not frame: # ?? Should we have set up a dummy globals # to have persistence? obj = eval(arg, None, None) else: obj = eval(arg, frame.f_g...
All python files caller s dir without the path and trailing. py
def pyfiles(callername, level=2): "All python files caller's dir without the path and trailing .py" d = os.path.dirname(callername) # Get the name of our directory. # A glob pattern that will get all *.py files but not __init__.py glob(os.path.join(d, '[a-zA-Z]*.py')) py_files = glob(os.path.joi...
Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number.
def adjust_frame(self, pos, absolute_pos): """Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number. A negative number indexes from the other end.""" if not self.curframe: Mmsg.errmsg(self, "No stack.") ...
We separate some of the common debugger command checks here: whether it makes sense to run the command in this execution state if the command has the right number of arguments and so on.
def ok_for_running(self, cmd_obj, name, cmd_hash): '''We separate some of the common debugger command checks here: whether it makes sense to run the command in this execution state, if the command has the right number of arguments and so on. ''' if hasattr(cmd_obj, 'execution_set...
Initialization done before entering the debugger - command loop. In particular we set up the call stack used for local variable lookup and frame/ up/ down commands.
def setup(self): """Initialization done before entering the debugger-command loop. In particular we set up the call stack used for local variable lookup and frame/up/down commands. We return True if we should NOT enter the debugger-command loop.""" self.forget() ...
Create an instance of each of the debugger commands. Commands are found by importing files in the directory command. Some files are excluded via an array set in __init__. For each of the remaining files we import them and scan for class names inside those files and for each class name we will create an instance of that...
def _populate_commands(self): """ Create an instance of each of the debugger commands. Commands are found by importing files in the directory 'command'. Some files are excluded via an array set in __init__. For each of the remaining files, we import them and scan for class names...
Populate self. commands
def _populate_cmd_lists(self): """ Populate self.commands""" self.commands = {} for cmd_instance in self.cmd_instances: cmd_name = cmd_instance.name self.commands[cmd_name] = cmd_instance pass return
Show where we are. GUI s and front - end interfaces often use this to update displays. So it is helpful to make sure we give at least some place that s located in a file.
def format_location(proc_obj): """Show where we are. GUI's and front-end interfaces often use this to update displays. So it is helpful to make sure we give at least some place that's located in a file. """ i_stack = proc_obj.curindex if i_stack is None or proc_obj.stack is None: return ...
used to write to a debugger that is connected to this server ; str written will have a newline added to it
def msg(self, msg): """ used to write to a debugger that is connected to this server; `str' written will have a newline added to it """ if hasattr(self.output, 'writeline'): self.output.writeline(msg) elif hasattr(self.output, 'writelines'): self.output.wr...
Execution status of the program.
def run(self, args): """Execution status of the program.""" mainfile = self.core.filename(None) if self.core.is_running(): if mainfile: part1 = "Python program '%s' is stopped" % mainfile else: part1 = 'Program is stopped' p...
List commands arranged in an aligned columns
def columnize_commands(self, commands): """List commands arranged in an aligned columns""" commands.sort() width = self.debugger.settings['width'] return columnize.columnize(commands, displaywidth=width, lineprefix=' ')
Convenience short - hand for self. debugger. intf [ - 1 ]. confirm
def confirm(self, msg, default=False): """ Convenience short-hand for self.debugger.intf[-1].confirm """ return self.debugger.intf[-1].confirm(msg, default)
Convenience short - hand for self. debugger. intf [ - 1 ]. errmsg
def errmsg(self, msg, opts={}): """ Convenience short-hand for self.debugger.intf[-1].errmsg """ try: return(self.debugger.intf[-1].errmsg(msg)) except EOFError: # FIXME: what do we do here? pass return None
Convenience short - hand for self. debugger. intf [ - 1 ]. msg
def msg(self, msg, opts={}): """ Convenience short-hand for self.debugger.intf[-1].msg """ try: return(self.debugger.intf[-1].msg(msg)) except EOFError: # FIXME: what do we do here? pass return None
Convenience short - hand for self. debugger. intf [ - 1 ]. msg_nocr
def msg_nocr(self, msg, opts={}): """ Convenience short-hand for self.debugger.intf[-1].msg_nocr """ try: return(self.debugger.intf[-1].msg_nocr(msg)) except EOFError: # FIXME: what do we do here? pass return None
Convert ReStructuredText and run through msg ()
def rst_msg(self, text, opts={}): """Convert ReStructuredText and run through msg()""" text = Mformat.rst_text(text, 'plain' == self.debugger.settings['highlight'], self.debugger.settings['width']) return self.msg(text)
Intended to be used going into post mortem routines. If sys. last_traceback is set we will return that and assume that this is what post - mortem will want. If sys. last_traceback has not been set then perhaps we * about * to raise an error and are fielding an exception. So assume that sys. exc_info () [ 2 ] is where w...
def get_last_or_frame_exception(): """Intended to be used going into post mortem routines. If sys.last_traceback is set, we will return that and assume that this is what post-mortem will want. If sys.last_traceback has not been set, then perhaps we *about* to raise an error and are fielding an exce...
Enter debugger read loop after your program has crashed.
def post_mortem(exc=None, frameno=1, dbg=None): """Enter debugger read loop after your program has crashed. exc is a triple like you get back from sys.exc_info. If no exc parameter, is supplied, the values from sys.last_type, sys.last_value, sys.last_traceback are used. And if these don't exist ei...
Closes both socket and server connection.
def close(self): """ Closes both socket and server connection. """ self.state = 'closing' if self.inout: self.inout.close() pass self.state = 'closing connection' if self.conn: self.conn.close() self.state = 'disconnected' retur...
This method the debugger uses to write. In contrast to writeline no newline is added to the end to str. Also msg doesn t have to be a string.
def write(self, msg): """ This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'. Also msg doesn't have to be a string. """ if self.state != 'connected': self.wait_for_connect() pass buffer = Mtcpf...
Find all starting matches in dictionary * aliases * that start with * prefix * but filter out any matches already in * expanded *.
def complete_token_filtered(aliases, prefix, expanded): """Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*.""" complete_ary = list(aliases.keys()) results = [cmd for cmd in complete_ary if cmd.startswith(pr...
Complete an arbitrary expression.
def complete_identifier(cmd, prefix): '''Complete an arbitrary expression.''' if not cmd.proc.curframe: return [None] # Collect globals and locals. It is usually not really sensible to also # complete builtins, and they clutter the namespace quite heavily, so we # leave them out. ns = cmd.proc....
Convenience short - hand for self. intf [ - 1 ]. errmsg
def errmsg(self, message, opts={}): """ Convenience short-hand for self.intf[-1].errmsg """ if 'plain' != self.debugger.settings['highlight']: message = colorize('standout', message) pass return(self.intf[-1].errmsg(message))
Convert ReStructuredText and run through msg ()
def rst_msg(self, text, opts={}): """Convert ReStructuredText and run through msg()""" from trepan.lib.format import rst_text text = rst_text(text, 'plain' == self.debugger.settings['highlight'], self.debugger.settings['width']) return self...
Invoke a debugger command from inside a python shell called inside the debugger.
def dbgr(self, string): '''Invoke a debugger command from inside a python shell called inside the debugger. ''' print('') self.proc.cmd_queue.append(string) self.proc.process_command() return
quit command when there s just one thread.
def nothread_quit(self, arg): """ quit command when there's just one thread. """ self.debugger.core.stop() self.debugger.core.execution_status = 'Quit command' self.proc.response['event'] = 'terminated' self.proc.response['name'] = 'status' self.proc.intf[-1].msg(self.p...
Parses arguments for the list command and returns the tuple: ( filename first line number last line number ) or sets these to None if there was some problem.
def parse_addr_list_cmd(proc, args, listsize=40): """Parses arguments for the "list" command and returns the tuple: (filename, first line number, last line number) or sets these to None if there was some problem.""" text = proc.current_command[len(args[0])+1:].strip() if text in frozenset(('', '.'...
Add frame_or_fn to the list of functions that are not to be debugged
def add_ignore(self, *frames_or_fns): """Add `frame_or_fn' to the list of functions that are not to be debugged""" for frame_or_fn in frames_or_fns: rc = self.ignore_filter.add_include(frame_or_fn) pass return rc
Turns filename into its canonic representation and returns this string. This allows a user to refer to a given file in one of several equivalent ways.
def canonic(self, filename): """ Turns `filename' into its canonic representation and returns this string. This allows a user to refer to a given file in one of several equivalent ways. Relative filenames need to be fully resolved, since the current working directory might chang...
Return filename or the basename of that depending on the basename setting
def filename(self, filename=None): """Return filename or the basename of that depending on the basename setting""" if filename is None: if self.debugger.mainpyfile: filename = self.debugger.mainpyfile else: return None if self.debug...
Return True if debugging is in progress.
def is_started(self): '''Return True if debugging is in progress.''' return (tracer.is_started() and not self.trace_hook_suspend and tracer.find_hook(self.trace_dispatch))
We ve already created a debugger object but here we start debugging in earnest. We can also turn off debugging ( but have the hooks suspended or not ) using stop.
def start(self, opts=None): """ We've already created a debugger object, but here we start debugging in earnest. We can also turn off debugging (but have the hooks suspended or not) using 'stop'. 'opts' is a hash of every known value you might want to set when starting the debug...
Does the magic to determine if we stop here and run a command processor or not. If so return True and set self. stop_reason ; if not return False.
def is_stop_here(self, frame, event, arg): """ Does the magic to determine if we stop here and run a command processor or not. If so, return True and set self.stop_reason; if not, return False. Determining factors can be whether a breakpoint was encountered, whether we are stepp...
Sets to stop on the next event that happens in frame frame.
def set_next(self, frame, step_ignore=0, step_events=None): "Sets to stop on the next event that happens in frame 'frame'." self.step_events = None # Consider all events self.stop_level = Mstack.count_frames(frame) self.last_level = self.stop_level self.last_fra...
A trace event occurred. Filter or pass the information to a specialized event processor. Note that there may be more filtering that goes on in the command processor ( e. g. to force a different line ). We could put that here but since that seems processor - specific I think it best to distribute the checks.
def trace_dispatch(self, frame, event, arg): '''A trace event occurred. Filter or pass the information to a specialized event processor. Note that there may be more filtering that goes on in the command processor (e.g. to force a different line). We could put that here, but since that se...
A mini stack trace routine for threads.
def stack_trace(self, f): """A mini stack trace routine for threads.""" while f: if (not self.core.ignore_filter.is_included(f) or self.settings['dbg_trepan']): s = Mstack.format_stack_entry(self, (f, f.f_lineno)) self.msg(" "*4 + s) ...
Get file information
def run(self, args): """Get file information""" if len(args) == 0: if not self.proc.curframe: self.errmsg("No frame - no default file.") return False filename = self.proc.curframe.f_code.co_filename else: filename = args[0] ...
** next ** [ ** + ** | ** - ** ] [ * count * ]
def run(self, args): """**next**[**+**|**-**] [*count*] Step one statement ignoring steps into function calls at this level. With an integer argument, perform `next` that many times. However if an exception occurs at this level, or we *return*, *yield* or the thread changes, we stop regardless of count. A su...
Check whether we should break here because of b. funcname.
def checkfuncname(b, frame): """Check whether we should break here because of `b.funcname`.""" if not b.funcname: # Breakpoint was set via line number. if b.line != frame.f_lineno: # Breakpoint was set at a line with a def statement and the function # defined is called: d...
remove breakpoint bp
def delete_breakpoint(self, bp): " remove breakpoint `bp'" bpnum = bp.number self.bpbynumber[bpnum] = None # No longer in list index = (bp.filename, bp.line) if index not in self.bplist: return False self.bplist[index].remove(bp) if not self.bplist[index]: ...
Remove a breakpoint given its breakpoint number.
def delete_breakpoint_by_number(self, bpnum): "Remove a breakpoint given its breakpoint number." success, msg, bp = self.get_breakpoint(bpnum) if not success: return False, msg self.delete_breakpoint(bp) return (True, '')
Enable or disable all breakpoints.
def en_disable_all_breakpoints(self, do_enable=True): "Enable or disable all breakpoints." bp_list = [bp for bp in self.bpbynumber if bp] bp_nums = [] if do_enable: endis = 'en' else: endis = 'dis' pass if not bp_list: retu...
Enable or disable a breakpoint given its breakpoint number.
def en_disable_breakpoint_by_number(self, bpnum, do_enable=True): "Enable or disable a breakpoint given its breakpoint number." success, msg, bp = self.get_breakpoint(bpnum) if not success: return success, msg if do_enable: endis = 'en' else: e...
Removes all breakpoints at a give filename and line number. Returns a list of breakpoints numbers deleted.
def delete_breakpoints_by_lineno(self, filename, lineno): """Removes all breakpoints at a give filename and line number. Returns a list of breakpoints numbers deleted. """ if (filename, lineno) not in self.bplist: return [] breakpoints = self.bplist[(filename, lineno)...
Determine which breakpoint for this file: line is to be acted upon.
def find_bp(self, filename, lineno, frame): """Determine which breakpoint for this file:line is to be acted upon. Called only if we know there is a bpt at this location. Returns breakpoint that was triggered and a flag that indicates if it is ok to delete a temporary breakpoint. ...
Use this to set what file to read from.
def open(self, inp, opts=None): """Use this to set what file to read from. """ if isinstance(inp, io.TextIOWrapper): self.input = inp elif isinstance(inp, 'string'.__class__): # FIXME self.name = inp self.input = open(inp, 'r') else: rais...
Read a line of input. Prompt and use_raw exist to be compatible with other input routines and are ignored. EOFError will be raised on EOF.
def readline(self, prompt='', use_raw=None): """Read a line of input. Prompt and use_raw exist to be compatible with other input routines and are ignored. EOFError will be raised on EOF. """ line = self.input.readline() if not line: raise EOFError return line.rstr...