Search is not available for this dataset
text
stringlengths
75
104k
def run(self, cmd, start_opts=None, globals_=None, locals_=None): """ Run debugger on string `cmd' using builtin function eval and if that builtin exec. Arguments `globals_' and `locals_' are the dictionaries to use for local and global variables. By default, the value of globals is glo...
def run_exec(self, cmd, start_opts=None, globals_=None, locals_=None): """ Run debugger on string `cmd' which will executed via the builtin function exec. Arguments `globals_' and `locals_' are the dictionaries to use for local and global variables. By default, the value of globals is gl...
def run_call(self, func, start_opts=None, *args, **kwds): """ Run debugger on function call: `func(*args, **kwds)' See also `run_eval' if what you want to run is an eval'able expression have that result returned and `run' if you want to debug a statment via exec. """ res...
def run_eval(self, expr, start_opts=None, globals_=None, locals_=None): """ Run debugger on string `expr' which will executed via the built-in Python function: eval; `globals_' and `locals_' are the dictionaries to use for local and global variables. If `globals' is not given, __main__._...
def run_script(self, filename, start_opts=None, globals_=None, locals_=None): """ Run debugger on Python script `filename'. The script may inspect sys.argv for command arguments. `globals_' and `locals_' are the dictionaries to use for local and global variables. If `g...
def arg_split(s, posix=False): """Split a command line's arguments in a shell-like manner returned as a list of lists. Use ';;' with white space to indicate separate commands. This is a modified version of the standard library's shlex.split() function, but with a default of posix=False for splittin...
def get_stack(f, t, botframe, proc_obj=None): """Return a stack of frames which the debugger will use for in showing backtraces and in frame switching. As such various frame that are really around may be excluded unless we are debugging the sebugger. Also we will add traceback frame on top if that e...
def run_hooks(obj, hooks, *args): """Run each function in `hooks' with args""" for hook in hooks: if hook(obj, *args): return True pass return False
def print_source_location_info(print_fn, filename, lineno, fn_name=None, f_lasti=None, remapped_file=None): """Print out a source location , e.g. the first line in line in: (/tmp.py:2 @21): <module> L -- 2 import sys,os (trepan3k) """ if remapped_f...
def print_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 F...
def event_processor(self, frame, event, event_arg, prompt='trepan3k'): 'command event processor: reading a commands do something with them.' self.frame = frame self.event = event self.event_arg = event_arg filename = frame.f_code.co_filename lineno = frame.f_li...
def forget(self): """ Remove memory of state variables set in the command processor """ self.stack = [] self.curindex = 0 self.curframe = None self.thread_name = None self.frame_thread_name = None return
def get_an_int(self, arg, msg_on_error, min_value=None, max_value=None): """Like cmdfns.get_an_int(), but if there's a stack frame use that in evaluation.""" ret_value = self.get_int_noerr(arg) if ret_value is None: if msg_on_error: self.errmsg(msg_on_error) ...
def get_int_noerr(self, arg): """Eval arg and it is an integer return the value. Otherwise return None""" if self.curframe: g = self.curframe.f_globals l = self.curframe.f_locals else: g = globals() l = locals() pass try...
def get_int(self, arg, min_value=0, default=1, cmdname=None, at_most=None): """If no argument use the default. If arg is a an integer between least min_value and at_most, use that. Otherwise report an error. If there's a stack frame use that in evaluation.""" if arg is N...
def ok_for_running(self, cmd_obj, name, nargs): """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'):...
def process_commands(self): """Handle debugger commands.""" if self.core.execution_status != 'No program': self.setup() self.location() pass leave_loop = run_hooks(self, self.preloop_hooks) self.continue_running = False while not leave_loop: ...
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() ...
def queue_startfile(self, cmdfile): """Arrange for file of debugger commands to get read in the process-command loop.""" expanded_cmdfile = os.path.expanduser(cmdfile) is_readable = Mfile.readable(expanded_cmdfile) if is_readable: self.cmd_queue.append('source ' + exp...
def read_history_file(self): """Read the command history file -- possibly.""" histfile = self.debugger.intf[-1].histfile try: import readline readline.read_history_file(histfile) except IOError: pass except ImportError: pass ...
def write_history_file(self): """Write the command history file -- possibly.""" settings = self.debugger.settings histfile = self.debugger.intf[-1].histfile if settings['hist_save']: try: import readline try: readline.write_...
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...
def _populate_cmd_lists(self): """ Populate self.lists and hashes: self.commands, and self.aliases, self.category """ self.commands = {} self.aliases = {} self.category = {} # self.short_help = {} for cmd_instance in self.cmd_instances: if not hasattr(...
def complete_token_filtered_with_next(aliases, prefix, expanded, commands): """Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*.""" complete_ary = list(aliases.keys()) expanded_ary = list(expanded.keys()) # result = [cm...
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 = aliases.keys() return [cmd for cmd in complete_ary if cmd.startswith(prefix)]
def next_token(str, start_pos): """Find the next token in str string from start_pos, we return the token and the next blank position after the token or str.size if this is the last token. Tokens are delimited by white space.""" look_at = str[start_pos:] match = re.search('\S', look_at) if ma...
def errmsg(self, msg, prefix="** "): """Common routine for reporting debugger error messages. """ # self.verbose shows lines so we don't have to duplicate info # here. Perhaps there should be a 'terse' mode to never show # position info. if not self.verbose: ...
def read_command(self, prompt=''): '''Script interface to read a command. `prompt' is a parameter for compatibilty and is ignored.''' self.input_lineno += 1 line = self.readline() if self.verbose: location = "%s line %s" % (self.script_name, self.input_lineno) ...
def close(self): """ Closes both input and output """ self.state = 'closing' if self.input: self.input.close() pass if self.output: self.output.close() pass self.state = 'disconnnected' return
def read_msg(self): """Read a line of input. EOFError will be raised on EOF. Note that we don't support prompting""" # FIXME: do we have to create and check a buffer for # lines? if self.state == 'active': if not self.input: self.input = open(self.in_...
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.state == 'active': if not self.output: self.output = open(self.out_name, 'w') pass pass...
def process_options(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.""" usage_str=""...
def dis(msg, msg_nocr, section, errmsg, x=None, start_line=-1, end_line=None, relative_pos = False, highlight='light', start_offset=0, end_offset=None, include_header=False): """Disassemble classes, methods, functions, or code. With no argument, disassemble the last traceback. """ last...
def disassemble(msg, msg_nocr, section, co, lasti=-1, start_line=-1, end_line=None, relative_pos=False, highlight='light', start_offset=0, end_offset=None): """Disassemble a code object.""" return disassemble_bytes(msg, msg_nocr, co.co_code, lasti, co.co_firstlineno, ...
def disassemble_bytes(orig_msg, orig_msg_nocr, code, lasti=-1, cur_line=0, start_line=-1, end_line=None, relative_pos=False, varnames=(), names=(), constants=(), cells=(), freevars=(), linestarts={}, highlight='light', start_offset=...
def count_frames(frame, count_start=0): "Return a count of the number of frames" count = -count_start while frame: count += 1 frame = frame.f_back return count
def format_stack_entry(dbg_obj, frame_lineno, lprefix=': ', include_location=True, color='plain'): """Format and return a stack entry gdb-style. Note: lprefix is not used. It is kept for compatibility. """ frame, lineno = frame_lineno filename = frame2file(dbg_obj.core, frame)...
def get_call_function_name(frame): """If f_back is looking at a call function, return the name for it. Otherwise return None""" f_back = frame.f_back if not f_back: return None if 'CALL_FUNCTION' != Mbytecode.op_at_frame(f_back): return None co = f_back.f_code code = co.co_cod...
def print_stack_trace(proc_obj, count=None, color='plain', opts={}): "Print count entries of the stack trace" if count is None: n=len(proc_obj.stack) else: n=min(len(proc_obj.stack), count) try: for i in range(n): print_stack_entry(proc_obj, i, color=color, opts=opts)...
def eval_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? val = eval(arg, None, None) else: val = eval(arg, fram...
def print_obj(arg, val, format=None, short=False): """Return a string representation of an object """ what = arg if format: what = format + ' ' + arg val = Mprint.printf(val, format) pass s = '%s = %s' % (what, val) if not short: s += '\n type = %s' % type(val) ...
def lookup(self, subcmd_prefix): """Find subcmd in self.subcmds""" for subcmd_name in list(self.subcmds.keys()): if subcmd_name.startswith(subcmd_prefix) \ and len(subcmd_prefix) >= \ self.subcmds[subcmd_name].__class__.min_abbrev: return self.su...
def short_help(self, subcmd_cb, subcmd_name, label=False): """Show short help for a subcommand.""" entry = self.lookup(subcmd_name) if entry: if label: prefix = entry.name else: prefix = '' pass if hasattr(entry,...
def add(self, subcmd_cb): """Add subcmd to the available subcommands for this object. It will have the supplied docstring, and subcmd_cb will be called when we want to run the command. min_len is the minimum length allowed to abbreviate the command. in_list indicates with the sho...
def run(self, subcmd_name, arg): """Run subcmd_name with args using obj for the environent""" entry=self.lookup(subcmd_name) if entry: entry['callback'](arg) else: self.cmdproc.undefined_cmd(entry.__class__.name, subcmd_name) pass return
def help(self, *args): """help for subcommands.""" print(args) subcmd_prefix = args[0] if not subcmd_prefix or len(subcmd_prefix) == 0: self.msg(self.doc) self.msg(""" List of %s subcommands: """ % (self.name)) for subcmd_name in self.list(): ...
def yield_sphinx_only_markup(lines): """ :param file_inp: a `filename` or ``sys.stdin``? :param file_out: a `filename` or ``sys.stdout`?` """ substs = [ ## Selected Sphinx-only Roles. # (r':abbr:`([^`]+)`', r'\1'), (r':ref:`([^`]+)`', r'`\1`_')...
def run_eval(expression, debug_opts=None, start_opts=None, globals_=None, locals_=None, tb_fn = None): """Evaluate the expression (given as a string) under debugger control starting with the statement subsequent to the place that this appears in your program. This is a wrapper to Debugger...
def run_call(func, debug_opts=None, start_opts=None, *args, **kwds): """Call the function (a function or method object, not a string) with the given arguments starting with the statement subsequent to the place that this appears in your program. When run_call() returns, it returns whatever the functio...
def run_exec(statement, debug_opts=None, start_opts=None, globals_=None, locals_=None): """Execute the statement (given as a string) under debugger control starting with the statement subsequent to the place that this run_call appears in your program. This is a wrapper to Debugger.run_exe...
def debug(dbg_opts=None, start_opts=None, post_mortem=True, step_ignore=1, level=0): """ Enter the debugger. Parameters ---------- level : how many stack frames go back. Usually it will be the default 0. But sometimes though there may be calls in setup to the debugger that you may want to skip. step_ig...
def list_categories(self): """List the command categories and a short description of each.""" self.section("Classes of commands:") cats = list(categories.keys()) cats.sort() for cat in cats: # Foo! iteritems() doesn't do sorting self.msg(" %-13s -- %s" % (cat, categ...
def show_category(self, category, args): """Show short help for all commands in `category'.""" n2cmd = self.proc.commands names = list(n2cmd.keys()) if len(args) == 1 and args[0] == '*': self.section("Commands in class %s:" % category) cmds = [cmd for cmd in names...
def run(self, args): """Current line number in source file""" # info line identifier if not self.proc.curframe: self.errmsg("No line number information available.") return if len(args) == 3: # lineinfo returns (item, file, lineno) or (None,) ...
def readable(path): """Test whether a path exists and is readable. Returns None for broken symbolic links or a failing stat() and False if the file exists but does not have read permission. True is returned if the file is readable.""" try: st = os.stat(path) return 0 != st.st_mode &...
def lookupmodule(name): """lookupmodule()->(module, file) translates a possibly incomplete file or module name into an absolute file name. None can be returned for either of the values positions of module or file when no or module or file is found. """ if sys.modules.get(name): return (s...
def parse_position(errmsg, arg): """parse_position(errmsg, arg)->(fn, name, lineno) Parse arg as [filename|module:]lineno Make sure it works for C:\foo\bar.py:12 """ colon = arg.rfind(':') if colon >= 0: filename = arg[:colon].rstrip() m, f = lookupmodule(filename) if no...
def find_debugged_frame(frame): """Find the first frame that is a debugged frame. We do this Generally we want traceback information without polluting it with debugger frames. We can tell these because those are frames on the top which don't have f_trace set. So we'll look back from the top to find ...
def map_thread_names(): '''Invert threading._active''' name2id = {} for thread_id in list(threading._active.keys()): thread = threading._active[thread_id] name = thread.getName() if name not in list(name2id.keys()): name2id[name] = thread_id pass pass ...
def open(self, inp, opts=None): """Use this to set where to read from. """ if isinstance(inp, list): self.input = inp else: raise IOError("Invalid input type (%s) for %s" % (type(inp), inp)) return
def readline(self, use_raw=None, prompt=''): """Read a line of input. EOFError will be raised on EOF. Note that we don't support prompting""" if self.closed: raise ValueError if 0 == len(self.input): self.closed = True raise EOFError line = self.input[0] ...
def open(self, output): """Use this to set where to write to. output can be a file object or a string. This code raises IOError on error. If another file was previously open upon calling this open, that will be stacked and will come back into use after a close_write(). "...
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.closed: raise ValueError if [] == self.output: self.output = [msg] else: self.output[-1] += msg ...
def default_configfile(base_filename): '''Return fully expanded configuration filename location for base_filename. python2 and python3 debuggers share the smae directory: ~/.config/trepan.py ''' file_dir = os.path.join(os.environ.get('HOME', '~'), '.config', 'trepanpy') file_dir = Mclifns.path_...
def add_startup_file(dbg_initfiles): """ Read debugger startup file(s): both python code and debugger profile to dbg_initfiles.""" startup_python_file = default_configfile('profile.py') if Mfile.readable(startup_python_file): with codecs.open(startup_python_file, 'r', encoding='utf8') as fp: ...
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 optparser is returned. sys_argv is also updated.""" ...
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): ...
def read_remote(self): '''Send a message back to the server (in contrast to the local user output channel).''' coded_line = self.inout.read_msg() if isinstance(coded_line, bytes): coded_line = coded_line.decode("utf-8") control = coded_line[0] remote_line = co...
def get_an_int(errmsg, arg, msg_on_error, min_value=None, max_value=None): """Another get_int() routine, this one simpler and less stylized than get_int(). We eval arg return it as an integer value or None if there was an error in parsing this. """ ret_value = None if arg: try: ...
def get_int(errmsg, arg, default=1, cmdname=None): """If arg is an int, use that otherwise take default.""" if arg: try: # eval() is used so we will allow arithmetic expressions, # variables etc. default = int(eval(arg)) except (SyntaxError, NameError, ValueEr...
def get_onoff(errmsg, arg, default=None, print_error=True): """Return True if arg is 'on' or 1 and False arg is 'off' or 0. Any other value is raises ValueError.""" if not arg: if default is None: if print_error: errmsg("Expecting 'on', 1, 'off', or 0. Got nothing.") ...
def run_set_bool(obj, args): """set a Boolean-valued debugger setting. 'obj' is a generally a subcommand that has 'name' and 'debugger.settings' attributes""" try: if 0 == len(args): args = ['on'] obj.debugger.settings[obj.name] = get_onoff(obj.errmsg, args[0]) except ValueError: ...
def run_set_int(obj, arg, msg_on_error, min_value=None, max_value=None): """set an Integer-valued debugger setting. 'obj' is a generally a subcommand that has 'name' and 'debugger.settings' attributes""" if '' == arg.strip(): obj.errmsg("You need to supply a number.") return obj.debugger...
def run_show_bool(obj, what=None): """Generic subcommand showing a boolean-valued debugger setting. 'obj' is generally a subcommand that has 'name' and 'debugger.setting' attributes.""" val = show_onoff(obj.debugger.settings[obj.name]) if not what: what = obj.name return obj.msg("%s is %s." % (w...
def run_show_int(obj, what=None): """Generic subcommand integer value display""" val = obj.debugger.settings[obj.name] if not what: what = obj.name return obj.msg("%s is %d." % (what, val))
def run_show_val(obj, name): """Generic subcommand value display""" val = obj.debugger.settings[obj.name] obj.msg("%s is %s." % (obj.name, obj.cmd.proc._saferepr(val),)) return False
def next_opcode(code, offset): '''Return the next opcode and offset as a tuple. Tuple (-100, -1000) is returned when reaching the end.''' n = len(code) while offset < n: op = code[offset] offset += 1 if op >= HAVE_ARGUMENT: offset += 2 pass yield o...
def is_def_stmt(line, frame): """Return True if we are looking at a def statement""" # Should really also check that operand of 'LOAD_CONST' is a code object return (line and _re_def.match(line) and op_at_frame(frame)=='LOAD_CONST' and stmt_contains_opcode(frame.f_code, frame.f_lineno, ...
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'))
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
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) ...
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
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...
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...
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.""" ...
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): ...
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__, ...
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...
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)
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 ...
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)
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 ...
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 + ' ' ...
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): ...
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
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)
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...
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...
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...
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...