INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Spawn a server process for this manager object
def start(self, initializer=None, initargs=()): '''Spawn a server process for this manager object''' assert self._state.value == State.INITIAL if (initializer is not None and not hasattr(initializer, '__call__')): raise TypeError('initializer must be a callable') ...
Return a wrapper for an fd.
def DupFd(fd): '''Return a wrapper for an fd.''' popen_obj = get_spawning_popen() if popen_obj is not None: return popen_obj.DupFd(popen_obj.duplicate_for_child(fd)) elif HAVE_SEND_HANDLE and sys.version_info[:2] > (3, 3): from multiprocessing import resource_sharer return resour...
Return the current ReusableExectutor instance.
def get_reusable_executor(max_workers=None, context=None, timeout=10, kill_workers=False, reuse="auto", job_reducers=None, result_reducers=None, initializer=None, initargs=()): """Return the current ReusableExectutor instance. Start ...
Wait for the cache to be empty before resizing the pool.
def _wait_job_completion(self): """Wait for the cache to be empty before resizing the pool.""" # Issue a warning to the user about the bad effect of this usage. if len(self._pending_work_items) > 0: warnings.warn("Trying to resize an executor with running jobs: " ...
Return info about parent needed by child to unpickle process object
def get_preparation_data(name, init_main_module=True): ''' Return info about parent needed by child to unpickle process object ''' _check_not_importing_main() d = dict( log_to_stderr=util._log_to_stderr, authkey=bytes(process.current_process().authkey), ) if util._logger is ...
Try to get current process ready to unpickle process object
def prepare(data): ''' Try to get current process ready to unpickle process object ''' if 'name' in data: process.current_process().name = data['name'] if 'authkey' in data: process.current_process().authkey = data['authkey'] if 'log_to_stderr' in data and data['log_to_stderr']...
Wait till an object in object_list is ready/ readable. Returns list of those objects which are ready/ readable.
def wait(object_list, timeout=None): ''' Wait till an object in object_list is ready/readable. Returns list of those objects which are ready/readable. ''' if timeout is not None: if timeout <= 0: return _poll(object_list, 0) else: deadline = monotonic() + time...
Close all the file descriptors except those in keep_fds.
def close_fds(keep_fds): # pragma: no cover """Close all the file descriptors except those in keep_fds.""" # Make sure to keep stdout and stderr open for logging purpose keep_fds = set(keep_fds).union([1, 2]) # We try to retrieve all the open fds try: open_fds = set(int(fd) for fd in os.l...
Terminate a process and its descendants.
def _recursive_terminate_without_psutil(process): """Terminate a process and its descendants. """ try: _recursive_terminate(process.pid) except OSError as e: warnings.warn("Failed to kill subprocesses on this platform. Please" "install psutil: https://github.com/gia...
Recursively kill the descendants of a process before killing it.
def _recursive_terminate(pid): """Recursively kill the descendants of a process before killing it. """ if sys.platform == "win32": # On windows, the taskkill function with option `/T` terminate a given # process pid and its children. try: subprocess.check_output( ...
Return a formated string with the exitcodes of terminated workers.
def get_exitcodes_terminated_worker(processes): """Return a formated string with the exitcodes of terminated workers. If necessary, wait (up to .25s) for the system to correctly set the exitcode of one terminated worker. """ patience = 5 # Catch the exitcode of the terminated workers. There sh...
Format a list of exit code with names of the signals if possible
def _format_exitcodes(exitcodes): """Format a list of exit code with names of the signals if possible""" str_exitcodes = ["{}({})".format(_get_exitcode_name(e), e) for e in exitcodes if e is not None] return "{" + ", ".join(str_exitcodes) + "}"
Run semaphore tracker.
def main(fd, verbose=0): '''Run semaphore tracker.''' # protect the process from ^C and "killall python" etc signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGTERM, signal.SIG_IGN) if _HAVE_SIGMASK: signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) for f i...
Make sure that semaphore tracker process is running.
def ensure_running(self): '''Make sure that semaphore tracker process is running. This can be run from any process. Usually a child process will use the semaphore created by its parent.''' with self._lock: if self._fd is not None: # semaphore tracker was lau...
A simple event processor that prints out events.
def event_processor(self, frame, event, arg): 'A simple event processor that prints out events.' out = self.debugger.intf[-1].output lineno = frame.f_lineno filename = self.core.canonic_filename(frame) filename = self.core.filename(filename) if not out: print(...
Program counter.
def run(self, args): """Program counter.""" mainfile = self.core.filename(None) if self.core.is_running(): curframe = self.proc.curframe if curframe: line_no = inspect.getlineno(curframe) offset = curframe.f_lasti self.msg(...
Almost a copy of code. interact Closely emulate the interactive Python interpreter.
def interact(banner=None, readfunc=None, my_locals=None, my_globals=None): """Almost a copy of code.interact Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readl...
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...
Adjust stack frame by pos positions. If absolute_pos then pos is an absolute number. Otherwise it is a relative number.
def adjust_frame(proc_obj, name, 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 proc_obj.curframe: proc_obj.errmsg("No stack.") return ...
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_list_cmd(proc, args, listsize=10): """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(('', '.', '+'...
Use this to set where to read from.
def open(self, inp, opts={}): """Use this to set where to read from. Set opts['try_lineedit'] if you want this input to interact with GNU-like readline library. By default, we will assume to try importing and using readline. If readline is not importable, line editing is not ava...
Read a line of input. EOFError will be raised on EOF.
def readline(self, use_raw=None, prompt=''): """Read a line of input. EOFError will be raised on EOF. Note: some user interfaces may decide to arrange to call DebuggerOutput.write() first with the prompt rather than pass it here.. If `use_raw' is set raw_input() will be used in that ...
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 globals () the current global variables. If locals_ is not given it becomes a copy of globals_.
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...
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 globals () the current global variables. If locals_ is not given it becomes a copy of globals_.
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...
Run debugger on function call: func ( * args ** kwds )
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...
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__. __dict__ ( the current global variables ) is used. If locals_ is not given it becomes a copy of globals_.
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__._...
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 globals is not given globals () ( the current global variables ) is used. If locals_ is not given it becomes a copy of globals_.
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...
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.
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...
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 exists.
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...
Run each function in hooks with args
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
Print out a source location e. g. the first line in line in: (/ tmp. py: 2
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...
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 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...
command event processor: reading a commands do something with them.
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...
Remove memory of state variables set in the command processor
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
Like cmdfns. get_an_int () but if there s a stack frame use that in evaluation.
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) ...
Eval arg and it is an integer return the value. Otherwise return None
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...
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.
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...
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, 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'):...
Handle debugger commands.
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: ...
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() ...
Arrange for file of debugger commands to get read in the process - command loop.
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...
Read the command history file -- possibly.
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 ...
Write the command history file -- possibly.
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_...
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. lists and hashes: self. commands and self. aliases self. category
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(...
Find all starting matches in dictionary * aliases * that start with * prefix * but filter out any matches already in * expanded *.
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...
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 = aliases.keys() return [cmd for cmd in complete_ary if cmd.startswith(prefix)]
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.
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...
Common routine for reporting debugger error messages.
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: ...
Script interface to read a command. prompt is a parameter for compatibilty and is ignored.
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) ...
Closes both input and output
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
Read a line of input. EOFError will be raised on EOF.
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_...
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.state == 'active': if not self.output: self.output = open(self.out_name, 'w') pass pass...
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(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=""...
Disassemble classes methods functions or code.
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...
Disassemble a code object.
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, ...
Disassemble byte string of code. If end_line is negative it counts the number of statement linestarts to use.
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=...
Return a count of the number of frames
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
Format and return a stack entry gdb - style. Note: lprefix is not used. It is kept for compatibility.
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)...
If f_back is looking at a call function return the name for it. Otherwise return None
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...
Print count entries of the stack trace
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)...
Return a string representation of an object
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...
Return a string representation of an object
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) ...
Find subcmd in self. subcmds
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...
Show short help for a subcommand.
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,...
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 show command will be run when giving a list of all sub commands of this o...
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...
Run subcmd_name with args using obj for the environent
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
help for subcommands.
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(): ...
: param file_inp: a filename or sys. stdin ?: param file_out: a filename or sys. stdout ?
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`_')...
Evaluate the expression ( given as a string ) under debugger control starting with the statement subsequent to the place that this appears in your program.
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...
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.
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...
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.
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...
Enter the debugger.
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...
List the command categories and a short description of each.
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...
Show short help for all commands in category.
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...
Current line number in source file
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,) ...
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.
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 &...
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.
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...
parse_position ( errmsg arg ) - > ( fn name lineno )
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...
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 the fist frame where f_trace is set.
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 ...
Invert threading. _active
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 ...
Use this to set where to read from.
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
Read a line of input. EOFError will be raised on EOF.
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] ...
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): """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(). "...
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.closed: raise ValueError if [] == self.output: self.output = [msg] else: self.output[-1] += msg ...
Return fully expanded configuration filename location for base_filename. python2 and python3 debuggers share the smae directory: ~/. config/ trepan. py
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_...
Read debugger startup file ( s ): both python code and debugger profile to dbg_initfiles.
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: ...
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 optparser is returned. 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): ...
Send a message back to the server ( in contrast to the local user output channel ).
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...
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.
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: ...
If arg is an int use that otherwise take default.
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...
Return True if arg is on or 1 and False arg is off or 0. Any other value is raises ValueError.
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.") ...
set a Boolean - valued debugger setting. obj is a generally a subcommand that has name and debugger. settings attributes
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: ...
set an Integer - valued debugger setting. obj is a generally a subcommand that has name and debugger. settings attributes
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...
Generic subcommand showing a boolean - valued debugger setting. obj is generally a subcommand that has name and debugger. setting attributes.
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...
Generic subcommand integer value display
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))
Generic subcommand value display
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
Return the next opcode and offset as a tuple. Tuple ( - 100 - 1000 ) is returned when reaching the end.
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...
Return True if we are looking at a def statement
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, ...