partition
stringclasses
3 values
func_name
stringlengths
1
134
docstring
stringlengths
1
46.9k
path
stringlengths
4
223
original_string
stringlengths
75
104k
code
stringlengths
75
104k
docstring_tokens
listlengths
1
1.97k
repo
stringlengths
7
55
language
stringclasses
1 value
url
stringlengths
87
315
code_tokens
listlengths
19
28.4k
sha
stringlengths
40
40
test
is_class_def
Return True if we are looking at a class definition statement
trepan/lib/bytecode.py
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 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'))
[ "Return", "True", "if", "we", "are", "looking", "at", "a", "class", "definition", "statement" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/bytecode.py#L100-L104
[ "def", "is_class_def", "(", "line", ",", "frame", ")", ":", "return", "(", "line", "and", "_re_class", ".", "match", "(", "line", ")", "and", "stmt_contains_opcode", "(", "frame", ".", "f_code", ",", "frame", ".", "f_lineno", ",", "'BUILD_CLASS'", ")", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
QuitCommand.nothread_quit
quit command when there's just one thread.
trepan/processor/command/quit.py
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 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", "there", "s", "just", "one", "thread", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/quit.py#L82-L87
[ "def", "nothread_quit", "(", "self", ",", "arg", ")", ":", "self", ".", "debugger", ".", "core", ".", "stop", "(", ")", "self", ".", "debugger", ".", "core", ".", "execution_status", "=", "'Quit command'", "raise", "Mexcept", ".", "DebuggerQuit" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
QuitCommand.threaded_quit
quit command when several threads are involved.
trepan/processor/command/quit.py
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) pass pass 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) pass pass raise Mexcept.DebuggerQuit
[ "quit", "command", "when", "several", "threads", "are", "involved", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/quit.py#L89-L98
[ "def", "threaded_quit", "(", "self", ",", "arg", ")", ":", "threading_list", "=", "threading", ".", "enumerate", "(", ")", "mythread", "=", "threading", ".", "currentThread", "(", ")", "for", "t", "in", "threading_list", ":", "if", "t", "!=", "mythread", ":", "ctype_async_raise", "(", "t", ",", "Mexcept", ".", "DebuggerQuit", ")", "pass", "pass", "raise", "Mexcept", ".", "DebuggerQuit" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
set_default_bg
Get bacground from default values based on the TERM environment variable
trepan/lib/term_background.py
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 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
[ "Get", "bacground", "from", "default", "values", "based", "on", "the", "TERM", "environment", "variable" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/term_background.py#L28-L37
[ "def", "set_default_bg", "(", ")", ":", "term", "=", "environ", ".", "get", "(", "'TERM'", ",", "None", ")", "if", "term", ":", "if", "(", "term", ".", "startswith", "(", "'xterm'", ",", ")", "or", "term", ".", "startswith", "(", "'eterm'", ")", "or", "term", "==", "'dtterm'", ")", ":", "return", "False", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
is_dark_rgb
Pass as parameters R G B values in hex On return, variable is_dark_bg is set
trepan/lib/term_background.py
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 (+ 65535 65535 65535)) # 382.5 = (* .6 (+ 65535 65535 65535)) print("midpoint", midpoint, 'vs', (16*5 + 16*g + 16*b)) midpoint = 383 if term and term == 'xterm-256color' else 117963 if ( (16*5 + 16*g + 16*b) < midpoint ): return True else: return False
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 (+ 65535 65535 65535)) # 382.5 = (* .6 (+ 65535 65535 65535)) print("midpoint", midpoint, 'vs', (16*5 + 16*g + 16*b)) midpoint = 383 if term and term == 'xterm-256color' else 117963 if ( (16*5 + 16*g + 16*b) < midpoint ): return True else: return False
[ "Pass", "as", "parameters", "R", "G", "B", "values", "in", "hex", "On", "return", "variable", "is_dark_bg", "is", "set" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/term_background.py#L40-L59
[ "def", "is_dark_rgb", "(", "r", ",", "g", ",", "b", ")", ":", "try", ":", "midpoint", "=", "int", "(", "environ", ".", "get", "(", "'TERMINAL_COLOR_MIDPOINT'", ",", "None", ")", ")", "except", ":", "pass", "if", "not", "midpoint", ":", "term", "=", "environ", ".", "get", "(", "'TERM'", ",", "None", ")", "# 117963 = (* .6 (+ 65535 65535 65535))", "# 382.5 = (* .6 (+ 65535 65535 65535))", "print", "(", "\"midpoint\"", ",", "midpoint", ",", "'vs'", ",", "(", "16", "*", "5", "+", "16", "*", "g", "+", "16", "*", "b", ")", ")", "midpoint", "=", "383", "if", "term", "and", "term", "==", "'xterm-256color'", "else", "117963", "if", "(", "(", "16", "*", "5", "+", "16", "*", "g", "+", "16", "*", "b", ")", "<", "midpoint", ")", ":", "return", "True", "else", ":", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
is_dark_color_fg_bg
Consult (environment) variables DARK_BG and COLORFGB On return, variable is_dark_bg is set
trepan/lib/term_background.py
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_fg_bg in ('15;0', '15;default;0'): return True elif color_fg_bg in ('0;15', '0;default;15' ): return False else: return True return None
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_fg_bg in ('15;0', '15;default;0'): return True elif color_fg_bg in ('0;15', '0;default;15' ): return False else: return True return None
[ "Consult", "(", "environment", ")", "variables", "DARK_BG", "and", "COLORFGB", "On", "return", "variable", "is_dark_bg", "is", "set" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/term_background.py#L62-L76
[ "def", "is_dark_color_fg_bg", "(", ")", ":", "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_fg_bg", "in", "(", "'15;0'", ",", "'15;default;0'", ")", ":", "return", "True", "elif", "color_fg_bg", "in", "(", "'0;15'", ",", "'0;default;15'", ")", ":", "return", "False", "else", ":", "return", "True", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
process_options
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.
trepan/bwcli.py
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.""" usage_str="""%prog [debugger-options] [python-script [script-options...]] Runs the extended python debugger""" # serverChoices = ('TCP','FIFO', None) optparser = OptionParser(usage=usage_str, option_list=option_list, version="%%prog version %s" % pkg_version) optparser.add_option("-F", "--fntrace", dest="fntrace", action="store_true", default=False, help="Show functions before executing them. " + "This option also sets --batch") optparser.add_option("--basename", dest="basename", action="store_true", default=False, help="Filenames strip off basename, " "(e.g. for regression tests)") optparser.add_option("--different", dest="different", action="store_true", default=True, help="Consecutive stops should have different " "positions") optparser.disable_interspersed_args() sys.argv = list(sys_argv) (opts, sys.argv) = optparser.parse_args() dbg_opts = {} return opts, dbg_opts, sys.argv
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.""" usage_str="""%prog [debugger-options] [python-script [script-options...]] Runs the extended python debugger""" # serverChoices = ('TCP','FIFO', None) optparser = OptionParser(usage=usage_str, option_list=option_list, version="%%prog version %s" % pkg_version) optparser.add_option("-F", "--fntrace", dest="fntrace", action="store_true", default=False, help="Show functions before executing them. " + "This option also sets --batch") optparser.add_option("--basename", dest="basename", action="store_true", default=False, help="Filenames strip off basename, " "(e.g. for regression tests)") optparser.add_option("--different", dest="different", action="store_true", default=True, help="Consecutive stops should have different " "positions") optparser.disable_interspersed_args() sys.argv = list(sys_argv) (opts, sys.argv) = optparser.parse_args() dbg_opts = {} return opts, dbg_opts, sys.argv
[ "Handle", "debugger", "options", ".", "Set", "option_list", "if", "you", "are", "writing", "another", "main", "program", "and", "want", "to", "extend", "the", "existing", "set", "of", "debugger", "options", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwcli.py#L36-L70
[ "def", "process_options", "(", "debugger_name", ",", "pkg_version", ",", "sys_argv", ",", "option_list", "=", "None", ")", ":", "usage_str", "=", "\"\"\"%prog [debugger-options] [python-script [script-options...]]\n\n Runs the extended python debugger\"\"\"", "# serverChoices = ('TCP','FIFO', None)", "optparser", "=", "OptionParser", "(", "usage", "=", "usage_str", ",", "option_list", "=", "option_list", ",", "version", "=", "\"%%prog version %s\"", "%", "pkg_version", ")", "optparser", ".", "add_option", "(", "\"-F\"", ",", "\"--fntrace\"", ",", "dest", "=", "\"fntrace\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Show functions before executing them. \"", "+", "\"This option also sets --batch\"", ")", "optparser", ".", "add_option", "(", "\"--basename\"", ",", "dest", "=", "\"basename\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "False", ",", "help", "=", "\"Filenames strip off basename, \"", "\"(e.g. for regression tests)\"", ")", "optparser", ".", "add_option", "(", "\"--different\"", ",", "dest", "=", "\"different\"", ",", "action", "=", "\"store_true\"", ",", "default", "=", "True", ",", "help", "=", "\"Consecutive stops should have different \"", "\"positions\"", ")", "optparser", ".", "disable_interspersed_args", "(", ")", "sys", ".", "argv", "=", "list", "(", "sys_argv", ")", "(", "opts", ",", "sys", ".", "argv", ")", "=", "optparser", ".", "parse_args", "(", ")", "dbg_opts", "=", "{", "}", "return", "opts", ",", "dbg_opts", ",", "sys", ".", "argv" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
_postprocess_options
Handle options (`opts') that feed into the debugger (`dbg')
trepan/bwcli.py
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): dbg.settings['printset'] = frozenset(print_events) pass for setting in ('basename', 'different',): dbg.settings[setting] = getattr(opts, setting) pass dbg.settings['highlight'] = 'plain' Mdebugger.debugger_obj = dbg return
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): dbg.settings['printset'] = frozenset(print_events) pass for setting in ('basename', 'different',): dbg.settings[setting] = getattr(opts, setting) pass dbg.settings['highlight'] = 'plain' Mdebugger.debugger_obj = dbg return
[ "Handle", "options", "(", "opts", ")", "that", "feed", "into", "the", "debugger", "(", "dbg", ")" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwcli.py#L73-L90
[ "def", "_postprocess_options", "(", "dbg", ",", "opts", ")", ":", "# 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", ")", ":", "dbg", ".", "settings", "[", "'printset'", "]", "=", "frozenset", "(", "print_events", ")", "pass", "for", "setting", "in", "(", "'basename'", ",", "'different'", ",", ")", ":", "dbg", ".", "settings", "[", "setting", "]", "=", "getattr", "(", "opts", ",", "setting", ")", "pass", "dbg", ".", "settings", "[", "'highlight'", "]", "=", "'plain'", "Mdebugger", ".", "debugger_obj", "=", "dbg", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
main
Routine which gets run if we were invoked directly
trepan/bwcli.py
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__, sys_argv) dbg_opts['orig_sys_argv'] = sys_argv dbg_opts['interface'] = Mbullwinkle.BWInterface() dbg_opts['processor'] = 'bullwinkle' if dbg is None: dbg = Mdebugger.Trepan(dbg_opts) dbg.core.add_ignore(main) pass _postprocess_options(dbg, opts) # process_options has munged sys.argv to remove any options that # options that belong to this debugger. The original options to # invoke the debugger and script are in global sys_argv if len(sys_argv) == 0: # No program given to debug. Set to go into a command loop # anyway mainpyfile = None else: mainpyfile = sys_argv[0] # Get script filename. if not os.path.isfile(mainpyfile): mainpyfile=Mclifns.whence_file(mainpyfile) is_readable = Mfile.readable(mainpyfile) if is_readable is None: print("%s: Python script file '%s' does not exist" % (__title__, mainpyfile,)) sys.exit(1) elif not is_readable: print("%s: Can't read Python script file '%s'" % (__title__, mainpyfile,)) sys.exit(1) return # If mainpyfile is an optimized Python script try to find and # use non-optimized alternative. mainpyfile_noopt = Mfile.file_pyc2py(mainpyfile) if mainpyfile != mainpyfile_noopt \ and Mfile.readable(mainpyfile_noopt): print("%s: Compiled Python script given and we can't use that." % __title__) print("%s: Substituting non-compiled name: %s" % ( __title__, mainpyfile_noopt,)) mainpyfile = mainpyfile_noopt pass # Replace trepan's dir with script's dir in front of # module search path. sys.path[0] = dbg.main_dirname = os.path.dirname(mainpyfile) # XXX If a signal has been received we continue in the loop, otherwise # the loop exits for some reason. dbg.sig_received = False # if not mainpyfile: # print('For now, you need to specify a Python script name!') # sys.exit(2) # pass while True: # Run the debugged script over and over again until we get it # right. try: if dbg.program_sys_argv and mainpyfile: normal_termination = dbg.run_script(mainpyfile) if not normal_termination: break else: dbg.core.execution_status = 'No program' dbg.core.processor.process_commands() pass dbg.core.execution_status = 'Terminated' dbg.intf[-1].msg("The program finished - quit or restart") dbg.core.processor.process_commands() except Mexcept.DebuggerQuit: break except Mexcept.DebuggerRestart: dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg(Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) else: break except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. break pass # Restore old sys.argv sys.argv = orig_sys_argv return
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__, sys_argv) dbg_opts['orig_sys_argv'] = sys_argv dbg_opts['interface'] = Mbullwinkle.BWInterface() dbg_opts['processor'] = 'bullwinkle' if dbg is None: dbg = Mdebugger.Trepan(dbg_opts) dbg.core.add_ignore(main) pass _postprocess_options(dbg, opts) # process_options has munged sys.argv to remove any options that # options that belong to this debugger. The original options to # invoke the debugger and script are in global sys_argv if len(sys_argv) == 0: # No program given to debug. Set to go into a command loop # anyway mainpyfile = None else: mainpyfile = sys_argv[0] # Get script filename. if not os.path.isfile(mainpyfile): mainpyfile=Mclifns.whence_file(mainpyfile) is_readable = Mfile.readable(mainpyfile) if is_readable is None: print("%s: Python script file '%s' does not exist" % (__title__, mainpyfile,)) sys.exit(1) elif not is_readable: print("%s: Can't read Python script file '%s'" % (__title__, mainpyfile,)) sys.exit(1) return # If mainpyfile is an optimized Python script try to find and # use non-optimized alternative. mainpyfile_noopt = Mfile.file_pyc2py(mainpyfile) if mainpyfile != mainpyfile_noopt \ and Mfile.readable(mainpyfile_noopt): print("%s: Compiled Python script given and we can't use that." % __title__) print("%s: Substituting non-compiled name: %s" % ( __title__, mainpyfile_noopt,)) mainpyfile = mainpyfile_noopt pass # Replace trepan's dir with script's dir in front of # module search path. sys.path[0] = dbg.main_dirname = os.path.dirname(mainpyfile) # XXX If a signal has been received we continue in the loop, otherwise # the loop exits for some reason. dbg.sig_received = False # if not mainpyfile: # print('For now, you need to specify a Python script name!') # sys.exit(2) # pass while True: # Run the debugged script over and over again until we get it # right. try: if dbg.program_sys_argv and mainpyfile: normal_termination = dbg.run_script(mainpyfile) if not normal_termination: break else: dbg.core.execution_status = 'No program' dbg.core.processor.process_commands() pass dbg.core.execution_status = 'Terminated' dbg.intf[-1].msg("The program finished - quit or restart") dbg.core.processor.process_commands() except Mexcept.DebuggerQuit: break except Mexcept.DebuggerRestart: dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg(Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) else: break except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. break pass # Restore old sys.argv sys.argv = orig_sys_argv return
[ "Routine", "which", "gets", "run", "if", "we", "were", "invoked", "directly" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwcli.py#L93-L194
[ "def", "main", "(", "dbg", "=", "None", ",", "sys_argv", "=", "list", "(", "sys", ".", "argv", ")", ")", ":", "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__", ",", "sys_argv", ")", "dbg_opts", "[", "'orig_sys_argv'", "]", "=", "sys_argv", "dbg_opts", "[", "'interface'", "]", "=", "Mbullwinkle", ".", "BWInterface", "(", ")", "dbg_opts", "[", "'processor'", "]", "=", "'bullwinkle'", "if", "dbg", "is", "None", ":", "dbg", "=", "Mdebugger", ".", "Trepan", "(", "dbg_opts", ")", "dbg", ".", "core", ".", "add_ignore", "(", "main", ")", "pass", "_postprocess_options", "(", "dbg", ",", "opts", ")", "# process_options has munged sys.argv to remove any options that", "# options that belong to this debugger. The original options to", "# invoke the debugger and script are in global sys_argv", "if", "len", "(", "sys_argv", ")", "==", "0", ":", "# No program given to debug. Set to go into a command loop", "# anyway", "mainpyfile", "=", "None", "else", ":", "mainpyfile", "=", "sys_argv", "[", "0", "]", "# Get script filename.", "if", "not", "os", ".", "path", ".", "isfile", "(", "mainpyfile", ")", ":", "mainpyfile", "=", "Mclifns", ".", "whence_file", "(", "mainpyfile", ")", "is_readable", "=", "Mfile", ".", "readable", "(", "mainpyfile", ")", "if", "is_readable", "is", "None", ":", "print", "(", "\"%s: Python script file '%s' does not exist\"", "%", "(", "__title__", ",", "mainpyfile", ",", ")", ")", "sys", ".", "exit", "(", "1", ")", "elif", "not", "is_readable", ":", "print", "(", "\"%s: Can't read Python script file '%s'\"", "%", "(", "__title__", ",", "mainpyfile", ",", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "# If mainpyfile is an optimized Python script try to find and", "# use non-optimized alternative.", "mainpyfile_noopt", "=", "Mfile", ".", "file_pyc2py", "(", "mainpyfile", ")", "if", "mainpyfile", "!=", "mainpyfile_noopt", "and", "Mfile", ".", "readable", "(", "mainpyfile_noopt", ")", ":", "print", "(", "\"%s: Compiled Python script given and we can't use that.\"", "%", "__title__", ")", "print", "(", "\"%s: Substituting non-compiled name: %s\"", "%", "(", "__title__", ",", "mainpyfile_noopt", ",", ")", ")", "mainpyfile", "=", "mainpyfile_noopt", "pass", "# Replace trepan's dir with script's dir in front of", "# module search path.", "sys", ".", "path", "[", "0", "]", "=", "dbg", ".", "main_dirname", "=", "os", ".", "path", ".", "dirname", "(", "mainpyfile", ")", "# XXX If a signal has been received we continue in the loop, otherwise", "# the loop exits for some reason.", "dbg", ".", "sig_received", "=", "False", "# if not mainpyfile:", "# print('For now, you need to specify a Python script name!')", "# sys.exit(2)", "# pass", "while", "True", ":", "# Run the debugged script over and over again until we get it", "# right.", "try", ":", "if", "dbg", ".", "program_sys_argv", "and", "mainpyfile", ":", "normal_termination", "=", "dbg", ".", "run_script", "(", "mainpyfile", ")", "if", "not", "normal_termination", ":", "break", "else", ":", "dbg", ".", "core", ".", "execution_status", "=", "'No program'", "dbg", ".", "core", ".", "processor", ".", "process_commands", "(", ")", "pass", "dbg", ".", "core", ".", "execution_status", "=", "'Terminated'", "dbg", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "\"The program finished - quit or restart\"", ")", "dbg", ".", "core", ".", "processor", ".", "process_commands", "(", ")", "except", "Mexcept", ".", "DebuggerQuit", ":", "break", "except", "Mexcept", ".", "DebuggerRestart", ":", "dbg", ".", "core", ".", "execution_status", "=", "'Restart requested'", "if", "dbg", ".", "program_sys_argv", ":", "sys", ".", "argv", "=", "list", "(", "dbg", ".", "program_sys_argv", ")", "part1", "=", "(", "'Restarting %s with arguments:'", "%", "dbg", ".", "core", ".", "filename", "(", "mainpyfile", ")", ")", "args", "=", "' '", ".", "join", "(", "dbg", ".", "program_sys_argv", "[", "1", ":", "]", ")", "dbg", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "Mmisc", ".", "wrapped_lines", "(", "part1", ",", "args", ",", "dbg", ".", "settings", "[", "'width'", "]", ")", ")", "else", ":", "break", "except", "SystemExit", ":", "# In most cases SystemExit does not warrant a post-mortem session.", "break", "pass", "# Restore old sys.argv", "sys", ".", "argv", "=", "orig_sys_argv", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
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
trepan/processor/command/show_subcmd/__demo_helper__.py
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(filename)[0]
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(filename)[0]
[ "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" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/show_subcmd/__demo_helper__.py#L5-L13
[ "def", "get_name", "(", ")", ":", "caller", "=", "sys", ".", "_getframe", "(", "2", ")", "filename", "=", "caller", ".", "f_code", ".", "co_filename", "filename", "=", "os", ".", "path", ".", "normcase", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "return", "os", ".", "path", ".", "splitext", "(", "filename", ")", "[", "0", "]" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
signature
return suitable frame signature to key display expressions off of.
trepan/lib/display.py
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 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)
[ "return", "suitable", "frame", "signature", "to", "key", "display", "expressions", "off", "of", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/display.py#L25-L29
[ "def", "signature", "(", "frame", ")", ":", "if", "not", "frame", ":", "return", "None", "code", "=", "frame", ".", "f_code", "return", "(", "code", ".", "co_name", ",", "code", ".", "co_filename", ",", "code", ".", "co_firstlineno", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DisplayMgr.all
List all display items; return 0 if none
trepan/lib/display.py
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 s.append(display.format()) return s
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 s.append(display.format()) return s
[ "List", "all", "display", "items", ";", "return", "0", "if", "none" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/display.py#L51-L62
[ "def", "all", "(", "self", ")", ":", "found", "=", "False", "s", "=", "[", "]", "for", "display", "in", "self", ".", "list", ":", "if", "not", "found", ":", "s", ".", "append", "(", "\"\"\"Auto-display expressions now in effect:\nNum Enb Expression\"\"\"", ")", "found", "=", "True", "pass", "s", ".", "append", "(", "display", ".", "format", "(", ")", ")", "return", "s" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DisplayMgr.delete_index
Delete display expression *display_number*
trepan/lib/display.py
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 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)
[ "Delete", "display", "expression", "*", "display_number", "*" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/display.py#L69-L74
[ "def", "delete_index", "(", "self", ",", "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", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DisplayMgr.display
display any items that are active
trepan/lib/display.py
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 pass return s
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 pass return s
[ "display", "any", "items", "that", "are", "active" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/display.py#L76-L86
[ "def", "display", "(", "self", ",", "frame", ")", ":", "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", "pass", "return", "s" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
Display.format
format display item
trepan/lib/display.py
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 + ' ' pass what += self.arg return '%3d: %s' % (self.number, what)
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 + ' ' pass what += self.arg return '%3d: %s' % (self.number, what)
[ "format", "display", "item" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/display.py#L120-L134
[ "def", "format", "(", "self", ",", "show_enabled", "=", "True", ")", ":", "what", "=", "''", "if", "show_enabled", ":", "if", "self", ".", "enabled", ":", "what", "+=", "' y '", "else", ":", "what", "+=", "' n '", "pass", "pass", "if", "self", ".", "fmt", ":", "what", "+=", "self", ".", "fmt", "+", "' '", "pass", "what", "+=", "self", ".", "arg", "return", "'%3d: %s'", "%", "(", "self", ".", "number", ",", "what", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TCPClient.read_msg
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.
trepan/inout/tcpclient.py
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): self.buf = self.inout.recv(Mtcpfns.TCP_MAX_PACKET) if 0 == (self.buf): self.state = 'disconnected' raise EOFError pass self.buf, data = Mtcpfns.unpack_msg(self.buf) return data.decode('utf-8') else: raise IOError("read_msg called in state: %s." % self.state)
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): self.buf = self.inout.recv(Mtcpfns.TCP_MAX_PACKET) if 0 == (self.buf): self.state = 'disconnected' raise EOFError pass self.buf, data = Mtcpfns.unpack_msg(self.buf) return data.decode('utf-8') else: raise IOError("read_msg called in state: %s." % self.state)
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/tcpclient.py#L84-L100
[ "def", "read_msg", "(", "self", ")", ":", "if", "self", ".", "state", "==", "'connected'", ":", "if", "0", "==", "len", "(", "self", ".", "buf", ")", ":", "self", ".", "buf", "=", "self", ".", "inout", ".", "recv", "(", "Mtcpfns", ".", "TCP_MAX_PACKET", ")", "if", "0", "==", "(", "self", ".", "buf", ")", ":", "self", ".", "state", "=", "'disconnected'", "raise", "EOFError", "pass", "self", ".", "buf", ",", "data", "=", "Mtcpfns", ".", "unpack_msg", "(", "self", ".", "buf", ")", "return", "data", ".", "decode", "(", "'utf-8'", ")", "else", ":", "raise", "IOError", "(", "\"read_msg called in state: %s.\"", "%", "self", ".", "state", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
debugger
Return the current debugger instance (if any), or creates a new one.
celery/ctrepan.py
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 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
[ "Return", "the", "current", "debugger", "instance", "(", "if", "any", ")", "or", "creates", "a", "new", "one", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/celery/ctrepan.py#L104-L110
[ "def", "debugger", "(", ")", ":", "dbg", "=", "_current", "[", "0", "]", "if", "dbg", "is", "None", "or", "not", "dbg", ".", "active", ":", "dbg", "=", "_current", "[", "0", "]", "=", "RemoteCeleryTrepan", "(", ")", "return", "dbg" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
debug
Set breakpoint at current location, or a specified frame
celery/ctrepan.py
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 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)
[ "Set", "breakpoint", "at", "current", "location", "or", "a", "specified", "frame" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/celery/ctrepan.py#L113-L122
[ "def", "debug", "(", "frame", "=", "None", ")", ":", "# ???", "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", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
cache_from_source
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.optimize is non-zero, then it will be .pyo. If debug_override is not None, then it must be a boolean and is used in place of sys.flags.optimize. If sys.implementation.cache_tag is None then NotImplementedError is raised.
trepan/processor/command/disassemble.py
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.optimize is non-zero, then it will be .pyo. If debug_override is not None, then it must be a boolean and is used in place of sys.flags.optimize. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ debug = not sys.flags.optimize if debug_override is None else debug_override if debug: suffixes = DEBUG_BYTECODE_SUFFIXES else: suffixes = OPTIMIZED_BYTECODE_SUFFIXES pass head, tail = os.path.split(path) base_filename, sep, _ = tail.partition('.') if not hasattr(sys, 'implementation'): # Python <= 3.2 raise NotImplementedError('No sys.implementation') tag = sys.implementation.cache_tag if tag is None: raise NotImplementedError('sys.implementation.cache_tag is None') filename = ''.join([base_filename, sep, tag, suffixes[0]]) return os.path.join(head, _PYCACHE, filename)
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.optimize is non-zero, then it will be .pyo. If debug_override is not None, then it must be a boolean and is used in place of sys.flags.optimize. If sys.implementation.cache_tag is None then NotImplementedError is raised. """ debug = not sys.flags.optimize if debug_override is None else debug_override if debug: suffixes = DEBUG_BYTECODE_SUFFIXES else: suffixes = OPTIMIZED_BYTECODE_SUFFIXES pass head, tail = os.path.split(path) base_filename, sep, _ = tail.partition('.') if not hasattr(sys, 'implementation'): # Python <= 3.2 raise NotImplementedError('No sys.implementation') tag = sys.implementation.cache_tag if tag is None: raise NotImplementedError('sys.implementation.cache_tag is None') filename = ''.join([base_filename, sep, tag, suffixes[0]]) return os.path.join(head, _PYCACHE, filename)
[ "Given", "the", "path", "to", "a", ".", "py", "file", "return", "the", "path", "to", "its", ".", "pyc", "/", ".", "pyo", "file", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/disassemble.py#L29-L57
[ "def", "cache_from_source", "(", "path", ",", "debug_override", "=", "None", ")", ":", "debug", "=", "not", "sys", ".", "flags", ".", "optimize", "if", "debug_override", "is", "None", "else", "debug_override", "if", "debug", ":", "suffixes", "=", "DEBUG_BYTECODE_SUFFIXES", "else", ":", "suffixes", "=", "OPTIMIZED_BYTECODE_SUFFIXES", "pass", "head", ",", "tail", "=", "os", ".", "path", ".", "split", "(", "path", ")", "base_filename", ",", "sep", ",", "_", "=", "tail", ".", "partition", "(", "'.'", ")", "if", "not", "hasattr", "(", "sys", ",", "'implementation'", ")", ":", "# Python <= 3.2", "raise", "NotImplementedError", "(", "'No sys.implementation'", ")", "tag", "=", "sys", ".", "implementation", ".", "cache_tag", "if", "tag", "is", "None", ":", "raise", "NotImplementedError", "(", "'sys.implementation.cache_tag is None'", ")", "filename", "=", "''", ".", "join", "(", "[", "base_filename", ",", "sep", ",", "tag", ",", "suffixes", "[", "0", "]", "]", ")", "return", "os", ".", "path", ".", "join", "(", "head", ",", "_PYCACHE", ",", "filename", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SubcommandMgr._load_debugger_subcommands
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 of that class. The set of DebuggerCommand class instances form set of possible debugger commands.
trepan/processor/command/base_submgr.py
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 and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" # Initialization cmd_instances = [] class_prefix = capitalize(name) # e.g. Info, Set, or Show module_dir = 'trepan.processor.command.%s_subcmd' % name mod = __import__(module_dir, None, None, ['*']) eval_cmd_template = 'command_mod.%s(self)' # Import, instantiate, and add classes for each of the # modules found in module_dir imported above. for module_name in mod.__modules__: import_name = module_dir + '.' + module_name try: command_mod = importlib.import_module(import_name) except ImportError: print(("Error importing name %s module %s: %s" % (import_name, module_name, sys.exc_info()[0]))) continue # Even though we tend not to do this, it is possible to # put more than one class into a module/file. So look for # all of them. classnames = [ classname for classname, classvalue in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != classname and classname.startswith(class_prefix)) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) self.cmds.add(instance) except: print("Error eval'ing class %s" % classname) pass pass pass return cmd_instances
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 and scan for class names inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" # Initialization cmd_instances = [] class_prefix = capitalize(name) # e.g. Info, Set, or Show module_dir = 'trepan.processor.command.%s_subcmd' % name mod = __import__(module_dir, None, None, ['*']) eval_cmd_template = 'command_mod.%s(self)' # Import, instantiate, and add classes for each of the # modules found in module_dir imported above. for module_name in mod.__modules__: import_name = module_dir + '.' + module_name try: command_mod = importlib.import_module(import_name) except ImportError: print(("Error importing name %s module %s: %s" % (import_name, module_name, sys.exc_info()[0]))) continue # Even though we tend not to do this, it is possible to # put more than one class into a module/file. So look for # all of them. classnames = [ classname for classname, classvalue in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != classname and classname.startswith(class_prefix)) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) self.cmds.add(instance) except: print("Error eval'ing class %s" % classname) pass pass pass return cmd_instances
[ "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", "of", "that", "class", ".", "The", "set", "of", "DebuggerCommand", "class", "instances", "form", "set", "of", "possible", "debugger", "commands", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_submgr.py#L59-L105
[ "def", "_load_debugger_subcommands", "(", "self", ",", "name", ")", ":", "# Initialization", "cmd_instances", "=", "[", "]", "class_prefix", "=", "capitalize", "(", "name", ")", "# e.g. Info, Set, or Show", "module_dir", "=", "'trepan.processor.command.%s_subcmd'", "%", "name", "mod", "=", "__import__", "(", "module_dir", ",", "None", ",", "None", ",", "[", "'*'", "]", ")", "eval_cmd_template", "=", "'command_mod.%s(self)'", "# Import, instantiate, and add classes for each of the", "# modules found in module_dir imported above.", "for", "module_name", "in", "mod", ".", "__modules__", ":", "import_name", "=", "module_dir", "+", "'.'", "+", "module_name", "try", ":", "command_mod", "=", "importlib", ".", "import_module", "(", "import_name", ")", "except", "ImportError", ":", "print", "(", "(", "\"Error importing name %s module %s: %s\"", "%", "(", "import_name", ",", "module_name", ",", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", ")", ")", "continue", "# Even though we tend not to do this, it is possible to", "# put more than one class into a module/file. So look for", "# all of them.", "classnames", "=", "[", "classname", "for", "classname", ",", "classvalue", "in", "inspect", ".", "getmembers", "(", "command_mod", ",", "inspect", ".", "isclass", ")", "if", "(", "'DebuggerCommand'", "!=", "classname", "and", "classname", ".", "startswith", "(", "class_prefix", ")", ")", "]", "for", "classname", "in", "classnames", ":", "eval_cmd", "=", "eval_cmd_template", "%", "classname", "try", ":", "instance", "=", "eval", "(", "eval_cmd", ")", "self", ".", "cmds", ".", "add", "(", "instance", ")", "except", ":", "print", "(", "\"Error eval'ing class %s\"", "%", "classname", ")", "pass", "pass", "pass", "return", "cmd_instances" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SubcommandMgr.help
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 a subcommand is given and found, then specific help for that is given. If 'commands' is given we will list the all the subcommands.
trepan/processor/command/base_submgr.py
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 a subcommand is given and found, then specific help for that is given. If 'commands' is given we will list the all the subcommands. """ if len(args) <= 2: # "help cmd". Give the general help for the command part. doc = self.__doc__ or self.run.__doc__ if doc: self.rst_msg(doc.rstrip('\n')) else: self.proc.intf[-1].errmsg('Sorry - author mess up. ' + 'No help registered for command' + self.name) pass return subcmd_name = args[2] if '*' == subcmd_name: self.section("List of subcommands for command '%s':" % self.name) self.msg(self.columnize_commands(self.cmds.list())) return # "help cmd subcmd". Give help specific for that subcommand. cmd = self.cmds.lookup(subcmd_name) if cmd: doc = cmd.__doc__ or cmd.run.__doc__ if doc: self.proc.rst_msg(doc.rstrip('\n')) else: self.proc.intf[-1] \ .errmsg('Sorry - author mess up. No help registered for ' 'subcommand %s of command %s' % (subcmd_name, self.name)) pass else: cmds = [c for c in self.cmds.list() if re.match('^' + subcmd_name, c) ] if cmds == []: self.errmsg("No %s subcommands found matching /^%s/. " "Try \"help\"." % (self.name, subcmd_name)) else: self.section("Subcommand(s) of \"%s\" matching /^%s/:" % (self.name, subcmd_name,)) self.msg_nocr(self.columnize_commands(cmds)) pass pass return
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 a subcommand is given and found, then specific help for that is given. If 'commands' is given we will list the all the subcommands. """ if len(args) <= 2: # "help cmd". Give the general help for the command part. doc = self.__doc__ or self.run.__doc__ if doc: self.rst_msg(doc.rstrip('\n')) else: self.proc.intf[-1].errmsg('Sorry - author mess up. ' + 'No help registered for command' + self.name) pass return subcmd_name = args[2] if '*' == subcmd_name: self.section("List of subcommands for command '%s':" % self.name) self.msg(self.columnize_commands(self.cmds.list())) return # "help cmd subcmd". Give help specific for that subcommand. cmd = self.cmds.lookup(subcmd_name) if cmd: doc = cmd.__doc__ or cmd.run.__doc__ if doc: self.proc.rst_msg(doc.rstrip('\n')) else: self.proc.intf[-1] \ .errmsg('Sorry - author mess up. No help registered for ' 'subcommand %s of command %s' % (subcmd_name, self.name)) pass else: cmds = [c for c in self.cmds.list() if re.match('^' + subcmd_name, c) ] if cmds == []: self.errmsg("No %s subcommands found matching /^%s/. " "Try \"help\"." % (self.name, subcmd_name)) else: self.section("Subcommand(s) of \"%s\" matching /^%s/:" % (self.name, subcmd_name,)) self.msg_nocr(self.columnize_commands(cmds)) pass pass return
[ "Give", "help", "for", "a", "command", "which", "has", "subcommands", ".", "This", "can", "be", "called", "in", "several", "ways", ":", "help", "cmd", "help", "cmd", "subcmd", "help", "cmd", "commands" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_submgr.py#L107-L162
[ "def", "help", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<=", "2", ":", "# \"help cmd\". Give the general help for the command part.", "doc", "=", "self", ".", "__doc__", "or", "self", ".", "run", ".", "__doc__", "if", "doc", ":", "self", ".", "rst_msg", "(", "doc", ".", "rstrip", "(", "'\\n'", ")", ")", "else", ":", "self", ".", "proc", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "'Sorry - author mess up. '", "+", "'No help registered for command'", "+", "self", ".", "name", ")", "pass", "return", "subcmd_name", "=", "args", "[", "2", "]", "if", "'*'", "==", "subcmd_name", ":", "self", ".", "section", "(", "\"List of subcommands for command '%s':\"", "%", "self", ".", "name", ")", "self", ".", "msg", "(", "self", ".", "columnize_commands", "(", "self", ".", "cmds", ".", "list", "(", ")", ")", ")", "return", "# \"help cmd subcmd\". Give help specific for that subcommand.", "cmd", "=", "self", ".", "cmds", ".", "lookup", "(", "subcmd_name", ")", "if", "cmd", ":", "doc", "=", "cmd", ".", "__doc__", "or", "cmd", ".", "run", ".", "__doc__", "if", "doc", ":", "self", ".", "proc", ".", "rst_msg", "(", "doc", ".", "rstrip", "(", "'\\n'", ")", ")", "else", ":", "self", ".", "proc", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "'Sorry - author mess up. No help registered for '", "'subcommand %s of command %s'", "%", "(", "subcmd_name", ",", "self", ".", "name", ")", ")", "pass", "else", ":", "cmds", "=", "[", "c", "for", "c", "in", "self", ".", "cmds", ".", "list", "(", ")", "if", "re", ".", "match", "(", "'^'", "+", "subcmd_name", ",", "c", ")", "]", "if", "cmds", "==", "[", "]", ":", "self", ".", "errmsg", "(", "\"No %s subcommands found matching /^%s/. \"", "\"Try \\\"help\\\".\"", "%", "(", "self", ".", "name", ",", "subcmd_name", ")", ")", "else", ":", "self", ".", "section", "(", "\"Subcommand(s) of \\\"%s\\\" matching /^%s/:\"", "%", "(", "self", ".", "name", ",", "subcmd_name", ",", ")", ")", "self", ".", "msg_nocr", "(", "self", ".", "columnize_commands", "(", "cmds", ")", ")", "pass", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SubcommandMgr.run
Ooops -- the debugger author didn't redefine this run docstring.
trepan/processor/command/base_submgr.py
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. self.section("List of %s commands (with minimum abbreviation in " "parenthesis):" % self.name) for subcmd_name in self.cmds.list(): # Some commands have lots of output. # they are excluded here because 'in_list' is false. subcmd = self.cmds.subcmds[subcmd_name] self.summary_help(subcmd_name, subcmd) pass return False subcmd_prefix = args[1] # We were given: cmd subcmd ... # Run that. subcmd = self.cmds.lookup(subcmd_prefix) if subcmd: nargs = len(args) - 2 if nargs < subcmd.min_args: self.errmsg(("Subcommand '%s %s' needs at least %d argument(s); " + "got %d.") % (self.name, subcmd.name, subcmd.min_args, nargs)) return False if subcmd.max_args is not None and nargs > subcmd.max_args: self.errmsg(("Subcommand '%s %s' takes at most %d argument(s); " + "got %d.") % (self.name, subcmd.name, subcmd.max_args, nargs)) return False return subcmd.run(args[2:]) else: return self.undefined_subcmd(self.name, subcmd_prefix) return
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. self.section("List of %s commands (with minimum abbreviation in " "parenthesis):" % self.name) for subcmd_name in self.cmds.list(): # Some commands have lots of output. # they are excluded here because 'in_list' is false. subcmd = self.cmds.subcmds[subcmd_name] self.summary_help(subcmd_name, subcmd) pass return False subcmd_prefix = args[1] # We were given: cmd subcmd ... # Run that. subcmd = self.cmds.lookup(subcmd_prefix) if subcmd: nargs = len(args) - 2 if nargs < subcmd.min_args: self.errmsg(("Subcommand '%s %s' needs at least %d argument(s); " + "got %d.") % (self.name, subcmd.name, subcmd.min_args, nargs)) return False if subcmd.max_args is not None and nargs > subcmd.max_args: self.errmsg(("Subcommand '%s %s' takes at most %d argument(s); " + "got %d.") % (self.name, subcmd.name, subcmd.max_args, nargs)) return False return subcmd.run(args[2:]) else: return self.undefined_subcmd(self.name, subcmd_prefix) return
[ "Ooops", "--", "the", "debugger", "author", "didn", "t", "redefine", "this", "run", "docstring", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_submgr.py#L175-L210
[ "def", "run", "(", "self", ",", "args", ")", ":", "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.", "self", ".", "section", "(", "\"List of %s commands (with minimum abbreviation in \"", "\"parenthesis):\"", "%", "self", ".", "name", ")", "for", "subcmd_name", "in", "self", ".", "cmds", ".", "list", "(", ")", ":", "# Some commands have lots of output.", "# they are excluded here because 'in_list' is false.", "subcmd", "=", "self", ".", "cmds", ".", "subcmds", "[", "subcmd_name", "]", "self", ".", "summary_help", "(", "subcmd_name", ",", "subcmd", ")", "pass", "return", "False", "subcmd_prefix", "=", "args", "[", "1", "]", "# We were given: cmd subcmd ...", "# Run that.", "subcmd", "=", "self", ".", "cmds", ".", "lookup", "(", "subcmd_prefix", ")", "if", "subcmd", ":", "nargs", "=", "len", "(", "args", ")", "-", "2", "if", "nargs", "<", "subcmd", ".", "min_args", ":", "self", ".", "errmsg", "(", "(", "\"Subcommand '%s %s' needs at least %d argument(s); \"", "+", "\"got %d.\"", ")", "%", "(", "self", ".", "name", ",", "subcmd", ".", "name", ",", "subcmd", ".", "min_args", ",", "nargs", ")", ")", "return", "False", "if", "subcmd", ".", "max_args", "is", "not", "None", "and", "nargs", ">", "subcmd", ".", "max_args", ":", "self", ".", "errmsg", "(", "(", "\"Subcommand '%s %s' takes at most %d argument(s); \"", "+", "\"got %d.\"", ")", "%", "(", "self", ".", "name", ",", "subcmd", ".", "name", ",", "subcmd", ".", "max_args", ",", "nargs", ")", ")", "return", "False", "return", "subcmd", ".", "run", "(", "args", "[", "2", ":", "]", ")", "else", ":", "return", "self", ".", "undefined_subcmd", "(", "self", ".", "name", ",", "subcmd_prefix", ")", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SubcommandMgr.undefined_subcmd
Error message when subcommand asked for but doesn't exist
trepan/processor/command/base_submgr.py
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
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
[ "Error", "message", "when", "subcommand", "asked", "for", "but", "doesn", "t", "exist" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_submgr.py#L219-L223
[ "def", "undefined_subcmd", "(", "self", ",", "cmd", ",", "subcmd", ")", ":", "self", ".", "proc", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "(", "'Undefined \"%s\" subcommand: \"%s\". '", "+", "'Try \"help %s *\".'", ")", "%", "(", "cmd", ",", "subcmd", ",", "cmd", ")", ")", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
runcode
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 always be caught. The caller should be prepared to deal with it.
trepan/processor/command/python.py
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 always be caught. The caller should be prepared to deal with it. """ try: exec(code_obj, obj.locals, obj.globals) except SystemExit: raise except: info = sys.exc_info() print("%s; %s" % (info[0], info[1])) else: pass return
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 always be caught. The caller should be prepared to deal with it. """ try: exec(code_obj, obj.locals, obj.globals) except SystemExit: raise except: info = sys.exc_info() print("%s; %s" % (info[0], info[1])) else: pass return
[ "Execute", "a", "code", "object", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/python.py#L170-L191
[ "def", "runcode", "(", "obj", ",", "code_obj", ")", ":", "try", ":", "exec", "(", "code_obj", ",", "obj", ".", "locals", ",", "obj", ".", "globals", ")", "except", "SystemExit", ":", "raise", "except", ":", "info", "=", "sys", ".", "exc_info", "(", ")", "print", "(", "\"%s; %s\"", "%", "(", "info", "[", "0", "]", ",", "info", "[", "1", "]", ")", ")", "else", ":", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DownCommand.run
**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`.
trepan/processor/command/down.py
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
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
[ "**", "down", "**", "[", "*", "count", "*", "]" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/down.py#L28-L40
[ "def", "run", "(", "self", ",", "args", ")", ":", "Mframe", ".", "adjust_relative", "(", "self", ".", "proc", ",", "self", ".", "name", ",", "args", ",", "self", ".", "signum", ")", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
resolve_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
trepan/processor/location.py
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: proc.errmsg("Don't have a stack to get location from") return INVALID_LOCATION filename = Mstack.frame2file(proc.core, curframe, canonic=False) lineno = inspect.getlineno(curframe) return Location(filename, lineno, False, None) assert isinstance(location, Location) is_address = False if proc.curframe: g = curframe.f_globals l = curframe.f_locals else: g = globals() l = locals() pass if location.method: # Validate arguments that can't be done in parsing filename = lineno = None msg = ('Object %s is not known yet as a function, ' % location.method) try: modfunc = eval(location.method, g, l) except: proc.errmsg(msg) return INVALID_LOCATION try: # Check if the converted string is a function or instance method if inspect.isfunction(modfunc) or hasattr(modfunc, 'im_func'): pass else: proc.errmsg(msg) return INVALID_LOCATION except: proc.errmsg(msg) return INVALID_LOCATION filename = proc.core.canonic(modfunc.__code__.co_filename) # FIXME: we may want to check lineno and # respect that in the future lineno = modfunc.__code__.co_firstlineno elif location.path: filename = proc.core.canonic(location.path) lineno = location.line_number modfunc = None msg = "%s is not known as a file" % location.path if not osp.isfile(filename): # See if argument is a module try: modfunc = eval(location.path, g, l) except: msg = ("Don't see '%s' as a existing file or as an module" % location.path) proc.errmsg(msg) return INVALID_LOCATION pass is_address = location.is_address if inspect.ismodule(modfunc): if hasattr(modfunc, '__file__'): filename = pyficache.pyc2py(modfunc.__file__) filename = proc.core.canonic(filename) if not lineno: # use first line of module file lineno = 1 is_address = False return Location(filename, lineno, is_address, modfunc) else: msg = ("module '%s' doesn't have a file associated with it" % location.path) proc.errmsg(msg) return INVALID_LOCATION maxline = pyficache.maxline(filename) if maxline and lineno > maxline: # NB: we use the gdb wording here proc.errmsg("Line number %d out of range; %s has %d lines." % (lineno, filename, maxline)) return INVALID_LOCATION elif location.line_number: filename = Mstack.frame2file(proc.core, curframe, canonic=False) lineno = location.line_number is_address = location.is_address modfunc = None return Location(filename, lineno, is_address, modfunc)
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: proc.errmsg("Don't have a stack to get location from") return INVALID_LOCATION filename = Mstack.frame2file(proc.core, curframe, canonic=False) lineno = inspect.getlineno(curframe) return Location(filename, lineno, False, None) assert isinstance(location, Location) is_address = False if proc.curframe: g = curframe.f_globals l = curframe.f_locals else: g = globals() l = locals() pass if location.method: # Validate arguments that can't be done in parsing filename = lineno = None msg = ('Object %s is not known yet as a function, ' % location.method) try: modfunc = eval(location.method, g, l) except: proc.errmsg(msg) return INVALID_LOCATION try: # Check if the converted string is a function or instance method if inspect.isfunction(modfunc) or hasattr(modfunc, 'im_func'): pass else: proc.errmsg(msg) return INVALID_LOCATION except: proc.errmsg(msg) return INVALID_LOCATION filename = proc.core.canonic(modfunc.__code__.co_filename) # FIXME: we may want to check lineno and # respect that in the future lineno = modfunc.__code__.co_firstlineno elif location.path: filename = proc.core.canonic(location.path) lineno = location.line_number modfunc = None msg = "%s is not known as a file" % location.path if not osp.isfile(filename): # See if argument is a module try: modfunc = eval(location.path, g, l) except: msg = ("Don't see '%s' as a existing file or as an module" % location.path) proc.errmsg(msg) return INVALID_LOCATION pass is_address = location.is_address if inspect.ismodule(modfunc): if hasattr(modfunc, '__file__'): filename = pyficache.pyc2py(modfunc.__file__) filename = proc.core.canonic(filename) if not lineno: # use first line of module file lineno = 1 is_address = False return Location(filename, lineno, is_address, modfunc) else: msg = ("module '%s' doesn't have a file associated with it" % location.path) proc.errmsg(msg) return INVALID_LOCATION maxline = pyficache.maxline(filename) if maxline and lineno > maxline: # NB: we use the gdb wording here proc.errmsg("Line number %d out of range; %s has %d lines." % (lineno, filename, maxline)) return INVALID_LOCATION elif location.line_number: filename = Mstack.frame2file(proc.core, curframe, canonic=False) lineno = location.line_number is_address = location.is_address modfunc = None return Location(filename, lineno, is_address, modfunc)
[ "Expand", "fields", "in", "Location", "namedtuple", ".", "If", ":", ".", ":", "get", "fields", "from", "stack", "function", "/", "module", ":", "get", "fields", "from", "evaluation", "/", "introspection", "location", "file", "and", "line", "number", ":", "use", "that" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/location.py#L23-L113
[ "def", "resolve_location", "(", "proc", ",", "location", ")", ":", "curframe", "=", "proc", ".", "curframe", "if", "location", "==", "'.'", ":", "if", "not", "curframe", ":", "proc", ".", "errmsg", "(", "\"Don't have a stack to get location from\"", ")", "return", "INVALID_LOCATION", "filename", "=", "Mstack", ".", "frame2file", "(", "proc", ".", "core", ",", "curframe", ",", "canonic", "=", "False", ")", "lineno", "=", "inspect", ".", "getlineno", "(", "curframe", ")", "return", "Location", "(", "filename", ",", "lineno", ",", "False", ",", "None", ")", "assert", "isinstance", "(", "location", ",", "Location", ")", "is_address", "=", "False", "if", "proc", ".", "curframe", ":", "g", "=", "curframe", ".", "f_globals", "l", "=", "curframe", ".", "f_locals", "else", ":", "g", "=", "globals", "(", ")", "l", "=", "locals", "(", ")", "pass", "if", "location", ".", "method", ":", "# Validate arguments that can't be done in parsing", "filename", "=", "lineno", "=", "None", "msg", "=", "(", "'Object %s is not known yet as a function, '", "%", "location", ".", "method", ")", "try", ":", "modfunc", "=", "eval", "(", "location", ".", "method", ",", "g", ",", "l", ")", "except", ":", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "try", ":", "# Check if the converted string is a function or instance method", "if", "inspect", ".", "isfunction", "(", "modfunc", ")", "or", "hasattr", "(", "modfunc", ",", "'im_func'", ")", ":", "pass", "else", ":", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "except", ":", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "filename", "=", "proc", ".", "core", ".", "canonic", "(", "modfunc", ".", "__code__", ".", "co_filename", ")", "# FIXME: we may want to check lineno and", "# respect that in the future", "lineno", "=", "modfunc", ".", "__code__", ".", "co_firstlineno", "elif", "location", ".", "path", ":", "filename", "=", "proc", ".", "core", ".", "canonic", "(", "location", ".", "path", ")", "lineno", "=", "location", ".", "line_number", "modfunc", "=", "None", "msg", "=", "\"%s is not known as a file\"", "%", "location", ".", "path", "if", "not", "osp", ".", "isfile", "(", "filename", ")", ":", "# See if argument is a module", "try", ":", "modfunc", "=", "eval", "(", "location", ".", "path", ",", "g", ",", "l", ")", "except", ":", "msg", "=", "(", "\"Don't see '%s' as a existing file or as an module\"", "%", "location", ".", "path", ")", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "pass", "is_address", "=", "location", ".", "is_address", "if", "inspect", ".", "ismodule", "(", "modfunc", ")", ":", "if", "hasattr", "(", "modfunc", ",", "'__file__'", ")", ":", "filename", "=", "pyficache", ".", "pyc2py", "(", "modfunc", ".", "__file__", ")", "filename", "=", "proc", ".", "core", ".", "canonic", "(", "filename", ")", "if", "not", "lineno", ":", "# use first line of module file", "lineno", "=", "1", "is_address", "=", "False", "return", "Location", "(", "filename", ",", "lineno", ",", "is_address", ",", "modfunc", ")", "else", ":", "msg", "=", "(", "\"module '%s' doesn't have a file associated with it\"", "%", "location", ".", "path", ")", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "maxline", "=", "pyficache", ".", "maxline", "(", "filename", ")", "if", "maxline", "and", "lineno", ">", "maxline", ":", "# NB: we use the gdb wording here", "proc", ".", "errmsg", "(", "\"Line number %d out of range; %s has %d lines.\"", "%", "(", "lineno", ",", "filename", ",", "maxline", ")", ")", "return", "INVALID_LOCATION", "elif", "location", ".", "line_number", ":", "filename", "=", "Mstack", ".", "frame2file", "(", "proc", ".", "core", ",", "curframe", ",", "canonic", "=", "False", ")", "lineno", "=", "location", ".", "line_number", "is_address", "=", "location", ".", "is_address", "modfunc", "=", "None", "return", "Location", "(", "filename", ",", "lineno", ",", "is_address", ",", "modfunc", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
resolve_address_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
trepan/processor/location.py
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 = Mstack.frame2file(proc.core, curframe, canonic=False) offset = curframe.f_lasti is_address = True return Location(filename, offset, False, None) assert isinstance(location, Location) is_address = True if proc.curframe: g = curframe.f_globals l = curframe.f_locals else: g = globals() l = locals() pass if location.method: # Validate arguments that can't be done in parsing filename = offset = None msg = ('Object %s is not known yet as a function, ' % location.method) try: modfunc = eval(location.method, g, l) except: proc.errmsg(msg) return INVALID_LOCATION try: # Check if the converted string is a function or instance method if inspect.isfunction(modfunc) or hasattr(modfunc, 'im_func'): pass else: proc.errmsg(msg) return INVALID_LOCATION except: proc.errmsg(msg) return INVALID_LOCATION filename = proc.core.canonic(modfunc.func_code.co_filename) # FIXME: we may want to check offset and # respect that in the future offset = 0 elif location.path: filename = proc.core.canonic(location.path) offset = location.line_number is_address = location.is_address modfunc = None msg = "%s is not known as a file" % location.path if not osp.isfile(filename): # See if argument is a module try: modfunc = eval(location.path, g, l) except: msg = ("Don't see '%s' as a existing file or as an module" % location.path) proc.errmsg(msg) return INVALID_LOCATION pass is_address = location.is_address if inspect.ismodule(modfunc): if hasattr(modfunc, '__file__'): filename = pyficache.pyc2py(modfunc.__file__) filename = proc.core.canonic(filename) if not offset: # use first offset of module file offset = 0 is_address = True return Location(filename, offset, is_address, modfunc) else: msg = ("module '%s' doesn't have a file associated with it" % location.path) proc.errmsg(msg) return INVALID_LOCATION maxline = pyficache.maxline(filename) if maxline and offset > maxline: # NB: we use the gdb wording here proc.errmsg("Line number %d out of range; %s has %d lines." % (offset, filename, maxline)) return INVALID_LOCATION elif location.line_number is not None: filename = Mstack.frame2file(proc.core, curframe, canonic=False) offset = location.line_number is_address = location.is_address modfunc = proc.list_object return Location(filename, offset, is_address, modfunc)
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 = Mstack.frame2file(proc.core, curframe, canonic=False) offset = curframe.f_lasti is_address = True return Location(filename, offset, False, None) assert isinstance(location, Location) is_address = True if proc.curframe: g = curframe.f_globals l = curframe.f_locals else: g = globals() l = locals() pass if location.method: # Validate arguments that can't be done in parsing filename = offset = None msg = ('Object %s is not known yet as a function, ' % location.method) try: modfunc = eval(location.method, g, l) except: proc.errmsg(msg) return INVALID_LOCATION try: # Check if the converted string is a function or instance method if inspect.isfunction(modfunc) or hasattr(modfunc, 'im_func'): pass else: proc.errmsg(msg) return INVALID_LOCATION except: proc.errmsg(msg) return INVALID_LOCATION filename = proc.core.canonic(modfunc.func_code.co_filename) # FIXME: we may want to check offset and # respect that in the future offset = 0 elif location.path: filename = proc.core.canonic(location.path) offset = location.line_number is_address = location.is_address modfunc = None msg = "%s is not known as a file" % location.path if not osp.isfile(filename): # See if argument is a module try: modfunc = eval(location.path, g, l) except: msg = ("Don't see '%s' as a existing file or as an module" % location.path) proc.errmsg(msg) return INVALID_LOCATION pass is_address = location.is_address if inspect.ismodule(modfunc): if hasattr(modfunc, '__file__'): filename = pyficache.pyc2py(modfunc.__file__) filename = proc.core.canonic(filename) if not offset: # use first offset of module file offset = 0 is_address = True return Location(filename, offset, is_address, modfunc) else: msg = ("module '%s' doesn't have a file associated with it" % location.path) proc.errmsg(msg) return INVALID_LOCATION maxline = pyficache.maxline(filename) if maxline and offset > maxline: # NB: we use the gdb wording here proc.errmsg("Line number %d out of range; %s has %d lines." % (offset, filename, maxline)) return INVALID_LOCATION elif location.line_number is not None: filename = Mstack.frame2file(proc.core, curframe, canonic=False) offset = location.line_number is_address = location.is_address modfunc = proc.list_object return Location(filename, offset, is_address, modfunc)
[ "Expand", "fields", "in", "Location", "namedtuple", ".", "If", ":", ".", ":", "get", "fields", "from", "stack", "function", "/", "module", ":", "get", "fields", "from", "evaluation", "/", "introspection", "location", "file", "and", "line", "number", ":", "use", "that" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/location.py#L115-L204
[ "def", "resolve_address_location", "(", "proc", ",", "location", ")", ":", "curframe", "=", "proc", ".", "curframe", "if", "location", "==", "'.'", ":", "filename", "=", "Mstack", ".", "frame2file", "(", "proc", ".", "core", ",", "curframe", ",", "canonic", "=", "False", ")", "offset", "=", "curframe", ".", "f_lasti", "is_address", "=", "True", "return", "Location", "(", "filename", ",", "offset", ",", "False", ",", "None", ")", "assert", "isinstance", "(", "location", ",", "Location", ")", "is_address", "=", "True", "if", "proc", ".", "curframe", ":", "g", "=", "curframe", ".", "f_globals", "l", "=", "curframe", ".", "f_locals", "else", ":", "g", "=", "globals", "(", ")", "l", "=", "locals", "(", ")", "pass", "if", "location", ".", "method", ":", "# Validate arguments that can't be done in parsing", "filename", "=", "offset", "=", "None", "msg", "=", "(", "'Object %s is not known yet as a function, '", "%", "location", ".", "method", ")", "try", ":", "modfunc", "=", "eval", "(", "location", ".", "method", ",", "g", ",", "l", ")", "except", ":", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "try", ":", "# Check if the converted string is a function or instance method", "if", "inspect", ".", "isfunction", "(", "modfunc", ")", "or", "hasattr", "(", "modfunc", ",", "'im_func'", ")", ":", "pass", "else", ":", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "except", ":", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "filename", "=", "proc", ".", "core", ".", "canonic", "(", "modfunc", ".", "func_code", ".", "co_filename", ")", "# FIXME: we may want to check offset and", "# respect that in the future", "offset", "=", "0", "elif", "location", ".", "path", ":", "filename", "=", "proc", ".", "core", ".", "canonic", "(", "location", ".", "path", ")", "offset", "=", "location", ".", "line_number", "is_address", "=", "location", ".", "is_address", "modfunc", "=", "None", "msg", "=", "\"%s is not known as a file\"", "%", "location", ".", "path", "if", "not", "osp", ".", "isfile", "(", "filename", ")", ":", "# See if argument is a module", "try", ":", "modfunc", "=", "eval", "(", "location", ".", "path", ",", "g", ",", "l", ")", "except", ":", "msg", "=", "(", "\"Don't see '%s' as a existing file or as an module\"", "%", "location", ".", "path", ")", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "pass", "is_address", "=", "location", ".", "is_address", "if", "inspect", ".", "ismodule", "(", "modfunc", ")", ":", "if", "hasattr", "(", "modfunc", ",", "'__file__'", ")", ":", "filename", "=", "pyficache", ".", "pyc2py", "(", "modfunc", ".", "__file__", ")", "filename", "=", "proc", ".", "core", ".", "canonic", "(", "filename", ")", "if", "not", "offset", ":", "# use first offset of module file", "offset", "=", "0", "is_address", "=", "True", "return", "Location", "(", "filename", ",", "offset", ",", "is_address", ",", "modfunc", ")", "else", ":", "msg", "=", "(", "\"module '%s' doesn't have a file associated with it\"", "%", "location", ".", "path", ")", "proc", ".", "errmsg", "(", "msg", ")", "return", "INVALID_LOCATION", "maxline", "=", "pyficache", ".", "maxline", "(", "filename", ")", "if", "maxline", "and", "offset", ">", "maxline", ":", "# NB: we use the gdb wording here", "proc", ".", "errmsg", "(", "\"Line number %d out of range; %s has %d lines.\"", "%", "(", "offset", ",", "filename", ",", "maxline", ")", ")", "return", "INVALID_LOCATION", "elif", "location", ".", "line_number", "is", "not", "None", ":", "filename", "=", "Mstack", ".", "frame2file", "(", "proc", ".", "core", ",", "curframe", ",", "canonic", "=", "False", ")", "offset", "=", "location", ".", "line_number", "is_address", "=", "location", ".", "is_address", "modfunc", "=", "proc", ".", "list_object", "return", "Location", "(", "filename", ",", "offset", ",", "is_address", ",", "modfunc", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
FrameCommand.find_and_set_debugged_frame
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.
trepan/processor/command/frame.py
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 = thread.getName() if (not self.settings['dbg_trepan'] and thread_name == Mthread.current_thread_name()): # The frame we came in on ('current_thread_name') is # the same as the one we want to switch to. In this case # we need to some debugger frames are in this stack so # we need to remove them. newframe = Mthread.find_debugged_frame(frame) if newframe is not None: frame = newframe pass # FIXME: else: we might be blocked on other threads which are # about to go into the debugger it not for the fact this one got there # first. Possibly in the future we want # to hide the blocks into threading of that locking code as well. # Set stack to new frame self.stack, self.curindex = Mcmdproc.get_stack(frame, None, self.proc) self.proc.stack, self.proc.curindex = self.stack, self.curindex self.proc.frame_thread_name = thread_name return
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 = thread.getName() if (not self.settings['dbg_trepan'] and thread_name == Mthread.current_thread_name()): # The frame we came in on ('current_thread_name') is # the same as the one we want to switch to. In this case # we need to some debugger frames are in this stack so # we need to remove them. newframe = Mthread.find_debugged_frame(frame) if newframe is not None: frame = newframe pass # FIXME: else: we might be blocked on other threads which are # about to go into the debugger it not for the fact this one got there # first. Possibly in the future we want # to hide the blocks into threading of that locking code as well. # Set stack to new frame self.stack, self.curindex = Mcmdproc.get_stack(frame, None, self.proc) self.proc.stack, self.proc.curindex = self.stack, self.curindex self.proc.frame_thread_name = thread_name return
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/frame.py#L76-L102
[ "def", "find_and_set_debugged_frame", "(", "self", ",", "frame", ",", "thread_id", ")", ":", "thread", "=", "threading", ".", "_active", "[", "thread_id", "]", "thread_name", "=", "thread", ".", "getName", "(", ")", "if", "(", "not", "self", ".", "settings", "[", "'dbg_trepan'", "]", "and", "thread_name", "==", "Mthread", ".", "current_thread_name", "(", ")", ")", ":", "# The frame we came in on ('current_thread_name') is", "# the same as the one we want to switch to. In this case", "# we need to some debugger frames are in this stack so", "# we need to remove them.", "newframe", "=", "Mthread", ".", "find_debugged_frame", "(", "frame", ")", "if", "newframe", "is", "not", "None", ":", "frame", "=", "newframe", "pass", "# FIXME: else: we might be blocked on other threads which are", "# about to go into the debugger it not for the fact this one got there", "# first. Possibly in the future we want", "# to hide the blocks into threading of that locking code as well.", "# Set stack to new frame", "self", ".", "stack", ",", "self", ".", "curindex", "=", "Mcmdproc", ".", "get_stack", "(", "frame", ",", "None", ",", "self", ".", "proc", ")", "self", ".", "proc", ".", "stack", ",", "self", ".", "proc", ".", "curindex", "=", "self", ".", "stack", ",", "self", ".", "curindex", "self", ".", "proc", ".", "frame_thread_name", "=", "thread_name", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
FrameCommand.one_arg_run
The simple case: thread frame switching has been done or is not needed and we have an explicit position number as a string
trepan/processor/command/frame.py
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" + " frame number. Got: %s") % position_str) if frame_num is None: return False i_stack = len(self.proc.stack) if i_stack == 0: self.errmsg('No frames recorded') return False if frame_num < -i_stack or frame_num > i_stack-1: self.errmsg(('Frame number has to be in the range %d to %d.' + ' Got: %d (%s).') % (-i_stack, i_stack-1, frame_num, position_str)) return False else: Mframe.adjust_frame(self.proc, 'frame', pos=frame_num, absolute_pos=True) return True return
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" + " frame number. Got: %s") % position_str) if frame_num is None: return False i_stack = len(self.proc.stack) if i_stack == 0: self.errmsg('No frames recorded') return False if frame_num < -i_stack or frame_num > i_stack-1: self.errmsg(('Frame number has to be in the range %d to %d.' + ' Got: %d (%s).') % (-i_stack, i_stack-1, frame_num, position_str)) return False else: Mframe.adjust_frame(self.proc, 'frame', pos=frame_num, absolute_pos=True) return True return
[ "The", "simple", "case", ":", "thread", "frame", "switching", "has", "been", "done", "or", "is", "not", "needed", "and", "we", "have", "an", "explicit", "position", "number", "as", "a", "string" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/frame.py#L104-L127
[ "def", "one_arg_run", "(", "self", ",", "position_str", ")", ":", "frame_num", "=", "self", ".", "proc", ".", "get_an_int", "(", "position_str", ",", "(", "\"The 'frame' command requires a\"", "+", "\" frame number. Got: %s\"", ")", "%", "position_str", ")", "if", "frame_num", "is", "None", ":", "return", "False", "i_stack", "=", "len", "(", "self", ".", "proc", ".", "stack", ")", "if", "i_stack", "==", "0", ":", "self", ".", "errmsg", "(", "'No frames recorded'", ")", "return", "False", "if", "frame_num", "<", "-", "i_stack", "or", "frame_num", ">", "i_stack", "-", "1", ":", "self", ".", "errmsg", "(", "(", "'Frame number has to be in the range %d to %d.'", "+", "' Got: %d (%s).'", ")", "%", "(", "-", "i_stack", ",", "i_stack", "-", "1", ",", "frame_num", ",", "position_str", ")", ")", "return", "False", "else", ":", "Mframe", ".", "adjust_frame", "(", "self", ".", "proc", ",", "'frame'", ",", "pos", "=", "frame_num", ",", "absolute_pos", "=", "True", ")", "return", "True", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
FrameCommand.get_from_thread_name_or_id
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.
trepan/processor/command/frame.py
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: # Must be a "frame" command with frame name, not a frame # number (or invalid command). name2id = Mthread.map_thread_names() if name_or_id == '.': name_or_id = Mthread.current_thread_name() pass thread_id = name2id.get(name_or_id) if thread_id is None: self.errmsg("I don't know about thread name %s." % name_or_id) return None, None pass # Above we should have set thread_id. Now see if we can # find it. threads = sys._current_frames() frame = threads.get(thread_id) if frame is None and report_error: self.errmsg("I don't know about thread number %s (%d)." % name_or_id, thread_id) # self.info_thread_terse() return None, None return frame, thread_id
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: # Must be a "frame" command with frame name, not a frame # number (or invalid command). name2id = Mthread.map_thread_names() if name_or_id == '.': name_or_id = Mthread.current_thread_name() pass thread_id = name2id.get(name_or_id) if thread_id is None: self.errmsg("I don't know about thread name %s." % name_or_id) return None, None pass # Above we should have set thread_id. Now see if we can # find it. threads = sys._current_frames() frame = threads.get(thread_id) if frame is None and report_error: self.errmsg("I don't know about thread number %s (%d)." % name_or_id, thread_id) # self.info_thread_terse() return None, None return frame, thread_id
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/frame.py#L129-L156
[ "def", "get_from_thread_name_or_id", "(", "self", ",", "name_or_id", ",", "report_error", "=", "True", ")", ":", "thread_id", "=", "self", ".", "proc", ".", "get_int_noerr", "(", "name_or_id", ")", "if", "thread_id", "is", "None", ":", "# Must be a \"frame\" command with frame name, not a frame", "# number (or invalid command).", "name2id", "=", "Mthread", ".", "map_thread_names", "(", ")", "if", "name_or_id", "==", "'.'", ":", "name_or_id", "=", "Mthread", ".", "current_thread_name", "(", ")", "pass", "thread_id", "=", "name2id", ".", "get", "(", "name_or_id", ")", "if", "thread_id", "is", "None", ":", "self", ".", "errmsg", "(", "\"I don't know about thread name %s.\"", "%", "name_or_id", ")", "return", "None", ",", "None", "pass", "# Above we should have set thread_id. Now see if we can", "# find it.", "threads", "=", "sys", ".", "_current_frames", "(", ")", "frame", "=", "threads", ".", "get", "(", "thread_id", ")", "if", "frame", "is", "None", "and", "report_error", ":", "self", ".", "errmsg", "(", "\"I don't know about thread number %s (%d).\"", "%", "name_or_id", ",", "thread_id", ")", "# self.info_thread_terse()", "return", "None", ",", "None", "return", "frame", ",", "thread_id" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
FrameCommand.run
Run a frame command. This routine is a little complex because we allow a number parameter variations.
trepan/processor/command/frame.py
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 {position | thread} name_or_id = args[1] frame, thread_id = self.get_from_thread_name_or_id(name_or_id, False) if frame is None: # Form should be: frame position position_str = name_or_id else: # Form should be: "frame thread" which means # "frame thread 0" position_str = '0' self.find_and_set_debugged_frame(frame, thread_id) pass elif len(args) == 3: # Form is: frame <thread> <position> name_or_id = args[1] position_str = args[2] frame, thread_id = self.get_from_thread_name_or_id(name_or_id) if frame is None: # Error message was given in routine return self.find_and_set_debugged_frame(frame, thread_id) pass self.one_arg_run(position_str) return False
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 {position | thread} name_or_id = args[1] frame, thread_id = self.get_from_thread_name_or_id(name_or_id, False) if frame is None: # Form should be: frame position position_str = name_or_id else: # Form should be: "frame thread" which means # "frame thread 0" position_str = '0' self.find_and_set_debugged_frame(frame, thread_id) pass elif len(args) == 3: # Form is: frame <thread> <position> name_or_id = args[1] position_str = args[2] frame, thread_id = self.get_from_thread_name_or_id(name_or_id) if frame is None: # Error message was given in routine return self.find_and_set_debugged_frame(frame, thread_id) pass self.one_arg_run(position_str) return False
[ "Run", "a", "frame", "command", ".", "This", "routine", "is", "a", "little", "complex", "because", "we", "allow", "a", "number", "parameter", "variations", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/frame.py#L158-L190
[ "def", "run", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "==", "1", ":", "# Form is: \"frame\" which means \"frame 0\"", "position_str", "=", "'0'", "elif", "len", "(", "args", ")", "==", "2", ":", "# Form is: \"frame {position | thread}", "name_or_id", "=", "args", "[", "1", "]", "frame", ",", "thread_id", "=", "self", ".", "get_from_thread_name_or_id", "(", "name_or_id", ",", "False", ")", "if", "frame", "is", "None", ":", "# Form should be: frame position", "position_str", "=", "name_or_id", "else", ":", "# Form should be: \"frame thread\" which means", "# \"frame thread 0\"", "position_str", "=", "'0'", "self", ".", "find_and_set_debugged_frame", "(", "frame", ",", "thread_id", ")", "pass", "elif", "len", "(", "args", ")", "==", "3", ":", "# Form is: frame <thread> <position>", "name_or_id", "=", "args", "[", "1", "]", "position_str", "=", "args", "[", "2", "]", "frame", ",", "thread_id", "=", "self", ".", "get_from_thread_name_or_id", "(", "name_or_id", ")", "if", "frame", "is", "None", ":", "# Error message was given in routine", "return", "self", ".", "find_and_set_debugged_frame", "(", "frame", ",", "thread_id", ")", "pass", "self", ".", "one_arg_run", "(", "position_str", ")", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
pprint_simple_array
Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not.
trepan/lib/pp.py
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[i]) in [bool, float, int]): numeric = False if not (type(val[i]) in [bool, float, int, bytes]): return False pass pass mess = columnize([repr(v) for v in val], opts={"arrange_array": True, "lineprefix": lineprefix, "displaywidth": int(displaywidth)-3, 'ljust': not numeric}) msg_nocr(mess) return True
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[i]) in [bool, float, int]): numeric = False if not (type(val[i]) in [bool, float, int, bytes]): return False pass pass mess = columnize([repr(v) for v in val], opts={"arrange_array": True, "lineprefix": lineprefix, "displaywidth": int(displaywidth)-3, 'ljust': not numeric}) msg_nocr(mess) return True
[ "Try", "to", "pretty", "print", "a", "simple", "case", "where", "a", "list", "is", "not", "nested", ".", "Return", "True", "if", "we", "can", "do", "it", "and", "False", "if", "not", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/pp.py#L40-L61
[ "def", "pprint_simple_array", "(", "val", ",", "displaywidth", ",", "msg_nocr", ",", "msg", ",", "lineprefix", "=", "''", ")", ":", "if", "type", "(", "val", ")", "!=", "list", ":", "return", "False", "numeric", "=", "True", "for", "i", "in", "range", "(", "len", "(", "val", ")", ")", ":", "if", "not", "(", "type", "(", "val", "[", "i", "]", ")", "in", "[", "bool", ",", "float", ",", "int", "]", ")", ":", "numeric", "=", "False", "if", "not", "(", "type", "(", "val", "[", "i", "]", ")", "in", "[", "bool", ",", "float", ",", "int", ",", "bytes", "]", ")", ":", "return", "False", "pass", "pass", "mess", "=", "columnize", "(", "[", "repr", "(", "v", ")", "for", "v", "in", "val", "]", ",", "opts", "=", "{", "\"arrange_array\"", ":", "True", ",", "\"lineprefix\"", ":", "lineprefix", ",", "\"displaywidth\"", ":", "int", "(", "displaywidth", ")", "-", "3", ",", "'ljust'", ":", "not", "numeric", "}", ")", "msg_nocr", "(", "mess", ")", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
main
Routine which gets run if we were invoked directly
trepan/cli.py
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__, VERSION, sys_argv) if opts.server is not None: if opts.server == 'tcp': connection_opts={'IO': 'TCP', 'PORT': opts.port} else: connection_opts={'IO': 'FIFO'} intf = Mserver.ServerInterface(connection_opts=connection_opts) dbg_opts['interface'] = intf if 'FIFO' == intf.server_type: print('Starting FIFO server for process %s.' % os.getpid()) elif 'TCP' == intf.server_type: print('Starting TCP server listening on port %s.' % intf.inout.PORT) pass elif opts.client: Mclient.run(opts, sys_argv) return dbg_opts['orig_sys_argv'] = orig_sys_argv if dbg is None: dbg = Mdebugger.Trepan(dbg_opts) dbg.core.add_ignore(main) pass Moptions._postprocess_options(dbg, opts) # process_options has munged sys.argv to remove any options that # options that belong to this debugger. The original options to # invoke the debugger and script are in global sys_argv if len(sys_argv) == 0: # No program given to debug. Set to go into a command loop # anyway mainpyfile = None else: mainpyfile = sys_argv[0] # Get script filename. if not osp.isfile(mainpyfile): mainpyfile=Mclifns.whence_file(mainpyfile) is_readable = Mfile.readable(mainpyfile) if is_readable is None: print("%s: Python script file '%s' does not exist" % (__title__, mainpyfile,)) sys.exit(1) elif not is_readable: print("%s: Can't read Python script file '%s'" % (__title__, mainpyfile, )) sys.exit(1) return if Mfile.is_compiled_py(mainpyfile): try: from xdis import load_module, PYTHON_VERSION, IS_PYPY (python_version, timestamp, magic_int, co, is_pypy, source_size) = load_module(mainpyfile, code_objects=None, fast_load=True) assert is_pypy == IS_PYPY assert python_version == PYTHON_VERSION, \ "bytecode is for version %s but we are version %s" % ( python_version, PYTHON_VERSION) # We should we check version magic_int py_file = co.co_filename if osp.isabs(py_file): try_file = py_file else: mainpydir = osp.dirname(mainpyfile) tag = sys.implementation.cache_tag dirnames = [osp.join(mainpydir, tag), mainpydir] + os.environ['PATH'].split(osp.pathsep) + ['.'] try_file = Mclifns.whence_file(py_file, dirnames) if osp.isfile(try_file): mainpyfile = try_file pass else: # Move onto the except branch raise IOError("Python file name embedded in code %s not found" % try_file) except IOError: try: from uncompyle6 import decompile_file except ImportError: print("%s: Compiled python file '%s', but uncompyle6 not found" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) return short_name = osp.basename(mainpyfile).strip('.pyc') fd = tempfile.NamedTemporaryFile(suffix='.py', prefix=short_name + "_", delete=False) old_write = fd.file.write def write_wrapper(*args, **kwargs): if isinstance(args[0], str): new_args = list(args) new_args[0] = args[0].encode('utf-8') old_write(*new_args, **kwargs) else: old_write(*args, **kwargs) fd.file.write = write_wrapper # from io import StringIO # linemap_io = StringIO() try: decompile_file(mainpyfile, fd.file, mapstream=fd) except: print("%s: error decompiling '%s'" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) return # # Get the line associations between the original and # # decompiled program # mapline = linemap_io.getvalue() # fd.write(mapline + "\n\n") # linemap = eval(mapline[3:]) mainpyfile = fd.name fd.close() # Since we are actually running the recreated source, # there is little no need to remap line numbers. # The mapping is given at the end of the file. # However we should consider adding this information # and original file name. print("%s: couldn't find Python source so we recreated it at '%s'" % (__title__, mainpyfile), file=sys.stderr) pass # If mainpyfile is an optimized Python script try to find and # use non-optimized alternative. mainpyfile_noopt = pyficache.pyc2py(mainpyfile) if mainpyfile != mainpyfile_noopt \ and Mfile.readable(mainpyfile_noopt): print("%s: Compiled Python script given and we can't use that." % __title__) print("%s: Substituting non-compiled name: %s" % ( __title__, mainpyfile_noopt,)) mainpyfile = mainpyfile_noopt pass # Replace trepan's dir with script's dir in front of # module search path. sys.path[0] = dbg.main_dirname = osp.dirname(mainpyfile) # XXX If a signal has been received we continue in the loop, otherwise # the loop exits for some reason. dbg.sig_received = False # if not mainpyfile: # print('For now, you need to specify a Python script name!') # sys.exit(2) # pass while True: # Run the debugged script over and over again until we get it # right. try: if dbg.program_sys_argv and mainpyfile: normal_termination = dbg.run_script(mainpyfile) if not normal_termination: break else: dbg.core.execution_status = 'No program' dbg.core.processor.process_commands() pass dbg.core.execution_status = 'Terminated' dbg.intf[-1].msg("The program finished - quit or restart") dbg.core.processor.process_commands() except Mexcept.DebuggerQuit: break except Mexcept.DebuggerRestart: dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg( Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) else: break except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. break pass # Restore old sys.argv sys.argv = orig_sys_argv return
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__, VERSION, sys_argv) if opts.server is not None: if opts.server == 'tcp': connection_opts={'IO': 'TCP', 'PORT': opts.port} else: connection_opts={'IO': 'FIFO'} intf = Mserver.ServerInterface(connection_opts=connection_opts) dbg_opts['interface'] = intf if 'FIFO' == intf.server_type: print('Starting FIFO server for process %s.' % os.getpid()) elif 'TCP' == intf.server_type: print('Starting TCP server listening on port %s.' % intf.inout.PORT) pass elif opts.client: Mclient.run(opts, sys_argv) return dbg_opts['orig_sys_argv'] = orig_sys_argv if dbg is None: dbg = Mdebugger.Trepan(dbg_opts) dbg.core.add_ignore(main) pass Moptions._postprocess_options(dbg, opts) # process_options has munged sys.argv to remove any options that # options that belong to this debugger. The original options to # invoke the debugger and script are in global sys_argv if len(sys_argv) == 0: # No program given to debug. Set to go into a command loop # anyway mainpyfile = None else: mainpyfile = sys_argv[0] # Get script filename. if not osp.isfile(mainpyfile): mainpyfile=Mclifns.whence_file(mainpyfile) is_readable = Mfile.readable(mainpyfile) if is_readable is None: print("%s: Python script file '%s' does not exist" % (__title__, mainpyfile,)) sys.exit(1) elif not is_readable: print("%s: Can't read Python script file '%s'" % (__title__, mainpyfile, )) sys.exit(1) return if Mfile.is_compiled_py(mainpyfile): try: from xdis import load_module, PYTHON_VERSION, IS_PYPY (python_version, timestamp, magic_int, co, is_pypy, source_size) = load_module(mainpyfile, code_objects=None, fast_load=True) assert is_pypy == IS_PYPY assert python_version == PYTHON_VERSION, \ "bytecode is for version %s but we are version %s" % ( python_version, PYTHON_VERSION) # We should we check version magic_int py_file = co.co_filename if osp.isabs(py_file): try_file = py_file else: mainpydir = osp.dirname(mainpyfile) tag = sys.implementation.cache_tag dirnames = [osp.join(mainpydir, tag), mainpydir] + os.environ['PATH'].split(osp.pathsep) + ['.'] try_file = Mclifns.whence_file(py_file, dirnames) if osp.isfile(try_file): mainpyfile = try_file pass else: # Move onto the except branch raise IOError("Python file name embedded in code %s not found" % try_file) except IOError: try: from uncompyle6 import decompile_file except ImportError: print("%s: Compiled python file '%s', but uncompyle6 not found" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) return short_name = osp.basename(mainpyfile).strip('.pyc') fd = tempfile.NamedTemporaryFile(suffix='.py', prefix=short_name + "_", delete=False) old_write = fd.file.write def write_wrapper(*args, **kwargs): if isinstance(args[0], str): new_args = list(args) new_args[0] = args[0].encode('utf-8') old_write(*new_args, **kwargs) else: old_write(*args, **kwargs) fd.file.write = write_wrapper # from io import StringIO # linemap_io = StringIO() try: decompile_file(mainpyfile, fd.file, mapstream=fd) except: print("%s: error decompiling '%s'" % (__title__, mainpyfile), file=sys.stderr) sys.exit(1) return # # Get the line associations between the original and # # decompiled program # mapline = linemap_io.getvalue() # fd.write(mapline + "\n\n") # linemap = eval(mapline[3:]) mainpyfile = fd.name fd.close() # Since we are actually running the recreated source, # there is little no need to remap line numbers. # The mapping is given at the end of the file. # However we should consider adding this information # and original file name. print("%s: couldn't find Python source so we recreated it at '%s'" % (__title__, mainpyfile), file=sys.stderr) pass # If mainpyfile is an optimized Python script try to find and # use non-optimized alternative. mainpyfile_noopt = pyficache.pyc2py(mainpyfile) if mainpyfile != mainpyfile_noopt \ and Mfile.readable(mainpyfile_noopt): print("%s: Compiled Python script given and we can't use that." % __title__) print("%s: Substituting non-compiled name: %s" % ( __title__, mainpyfile_noopt,)) mainpyfile = mainpyfile_noopt pass # Replace trepan's dir with script's dir in front of # module search path. sys.path[0] = dbg.main_dirname = osp.dirname(mainpyfile) # XXX If a signal has been received we continue in the loop, otherwise # the loop exits for some reason. dbg.sig_received = False # if not mainpyfile: # print('For now, you need to specify a Python script name!') # sys.exit(2) # pass while True: # Run the debugged script over and over again until we get it # right. try: if dbg.program_sys_argv and mainpyfile: normal_termination = dbg.run_script(mainpyfile) if not normal_termination: break else: dbg.core.execution_status = 'No program' dbg.core.processor.process_commands() pass dbg.core.execution_status = 'Terminated' dbg.intf[-1].msg("The program finished - quit or restart") dbg.core.processor.process_commands() except Mexcept.DebuggerQuit: break except Mexcept.DebuggerRestart: dbg.core.execution_status = 'Restart requested' if dbg.program_sys_argv: sys.argv = list(dbg.program_sys_argv) part1 = ('Restarting %s with arguments:' % dbg.core.filename(mainpyfile)) args = ' '.join(dbg.program_sys_argv[1:]) dbg.intf[-1].msg( Mmisc.wrapped_lines(part1, args, dbg.settings['width'])) else: break except SystemExit: # In most cases SystemExit does not warrant a post-mortem session. break pass # Restore old sys.argv sys.argv = orig_sys_argv return
[ "Routine", "which", "gets", "run", "if", "we", "were", "invoked", "directly" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/cli.py#L41-L242
[ "def", "main", "(", "dbg", "=", "None", ",", "sys_argv", "=", "list", "(", "sys", ".", "argv", ")", ")", ":", "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__", ",", "VERSION", ",", "sys_argv", ")", "if", "opts", ".", "server", "is", "not", "None", ":", "if", "opts", ".", "server", "==", "'tcp'", ":", "connection_opts", "=", "{", "'IO'", ":", "'TCP'", ",", "'PORT'", ":", "opts", ".", "port", "}", "else", ":", "connection_opts", "=", "{", "'IO'", ":", "'FIFO'", "}", "intf", "=", "Mserver", ".", "ServerInterface", "(", "connection_opts", "=", "connection_opts", ")", "dbg_opts", "[", "'interface'", "]", "=", "intf", "if", "'FIFO'", "==", "intf", ".", "server_type", ":", "print", "(", "'Starting FIFO server for process %s.'", "%", "os", ".", "getpid", "(", ")", ")", "elif", "'TCP'", "==", "intf", ".", "server_type", ":", "print", "(", "'Starting TCP server listening on port %s.'", "%", "intf", ".", "inout", ".", "PORT", ")", "pass", "elif", "opts", ".", "client", ":", "Mclient", ".", "run", "(", "opts", ",", "sys_argv", ")", "return", "dbg_opts", "[", "'orig_sys_argv'", "]", "=", "orig_sys_argv", "if", "dbg", "is", "None", ":", "dbg", "=", "Mdebugger", ".", "Trepan", "(", "dbg_opts", ")", "dbg", ".", "core", ".", "add_ignore", "(", "main", ")", "pass", "Moptions", ".", "_postprocess_options", "(", "dbg", ",", "opts", ")", "# process_options has munged sys.argv to remove any options that", "# options that belong to this debugger. The original options to", "# invoke the debugger and script are in global sys_argv", "if", "len", "(", "sys_argv", ")", "==", "0", ":", "# No program given to debug. Set to go into a command loop", "# anyway", "mainpyfile", "=", "None", "else", ":", "mainpyfile", "=", "sys_argv", "[", "0", "]", "# Get script filename.", "if", "not", "osp", ".", "isfile", "(", "mainpyfile", ")", ":", "mainpyfile", "=", "Mclifns", ".", "whence_file", "(", "mainpyfile", ")", "is_readable", "=", "Mfile", ".", "readable", "(", "mainpyfile", ")", "if", "is_readable", "is", "None", ":", "print", "(", "\"%s: Python script file '%s' does not exist\"", "%", "(", "__title__", ",", "mainpyfile", ",", ")", ")", "sys", ".", "exit", "(", "1", ")", "elif", "not", "is_readable", ":", "print", "(", "\"%s: Can't read Python script file '%s'\"", "%", "(", "__title__", ",", "mainpyfile", ",", ")", ")", "sys", ".", "exit", "(", "1", ")", "return", "if", "Mfile", ".", "is_compiled_py", "(", "mainpyfile", ")", ":", "try", ":", "from", "xdis", "import", "load_module", ",", "PYTHON_VERSION", ",", "IS_PYPY", "(", "python_version", ",", "timestamp", ",", "magic_int", ",", "co", ",", "is_pypy", ",", "source_size", ")", "=", "load_module", "(", "mainpyfile", ",", "code_objects", "=", "None", ",", "fast_load", "=", "True", ")", "assert", "is_pypy", "==", "IS_PYPY", "assert", "python_version", "==", "PYTHON_VERSION", ",", "\"bytecode is for version %s but we are version %s\"", "%", "(", "python_version", ",", "PYTHON_VERSION", ")", "# We should we check version magic_int", "py_file", "=", "co", ".", "co_filename", "if", "osp", ".", "isabs", "(", "py_file", ")", ":", "try_file", "=", "py_file", "else", ":", "mainpydir", "=", "osp", ".", "dirname", "(", "mainpyfile", ")", "tag", "=", "sys", ".", "implementation", ".", "cache_tag", "dirnames", "=", "[", "osp", ".", "join", "(", "mainpydir", ",", "tag", ")", ",", "mainpydir", "]", "+", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "osp", ".", "pathsep", ")", "+", "[", "'.'", "]", "try_file", "=", "Mclifns", ".", "whence_file", "(", "py_file", ",", "dirnames", ")", "if", "osp", ".", "isfile", "(", "try_file", ")", ":", "mainpyfile", "=", "try_file", "pass", "else", ":", "# Move onto the except branch", "raise", "IOError", "(", "\"Python file name embedded in code %s not found\"", "%", "try_file", ")", "except", "IOError", ":", "try", ":", "from", "uncompyle6", "import", "decompile_file", "except", "ImportError", ":", "print", "(", "\"%s: Compiled python file '%s', but uncompyle6 not found\"", "%", "(", "__title__", ",", "mainpyfile", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "return", "short_name", "=", "osp", ".", "basename", "(", "mainpyfile", ")", ".", "strip", "(", "'.pyc'", ")", "fd", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.py'", ",", "prefix", "=", "short_name", "+", "\"_\"", ",", "delete", "=", "False", ")", "old_write", "=", "fd", ".", "file", ".", "write", "def", "write_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "args", "[", "0", "]", ",", "str", ")", ":", "new_args", "=", "list", "(", "args", ")", "new_args", "[", "0", "]", "=", "args", "[", "0", "]", ".", "encode", "(", "'utf-8'", ")", "old_write", "(", "*", "new_args", ",", "*", "*", "kwargs", ")", "else", ":", "old_write", "(", "*", "args", ",", "*", "*", "kwargs", ")", "fd", ".", "file", ".", "write", "=", "write_wrapper", "# from io import StringIO", "# linemap_io = StringIO()", "try", ":", "decompile_file", "(", "mainpyfile", ",", "fd", ".", "file", ",", "mapstream", "=", "fd", ")", "except", ":", "print", "(", "\"%s: error decompiling '%s'\"", "%", "(", "__title__", ",", "mainpyfile", ")", ",", "file", "=", "sys", ".", "stderr", ")", "sys", ".", "exit", "(", "1", ")", "return", "# # Get the line associations between the original and", "# # decompiled program", "# mapline = linemap_io.getvalue()", "# fd.write(mapline + \"\\n\\n\")", "# linemap = eval(mapline[3:])", "mainpyfile", "=", "fd", ".", "name", "fd", ".", "close", "(", ")", "# Since we are actually running the recreated source,", "# there is little no need to remap line numbers.", "# The mapping is given at the end of the file.", "# However we should consider adding this information", "# and original file name.", "print", "(", "\"%s: couldn't find Python source so we recreated it at '%s'\"", "%", "(", "__title__", ",", "mainpyfile", ")", ",", "file", "=", "sys", ".", "stderr", ")", "pass", "# If mainpyfile is an optimized Python script try to find and", "# use non-optimized alternative.", "mainpyfile_noopt", "=", "pyficache", ".", "pyc2py", "(", "mainpyfile", ")", "if", "mainpyfile", "!=", "mainpyfile_noopt", "and", "Mfile", ".", "readable", "(", "mainpyfile_noopt", ")", ":", "print", "(", "\"%s: Compiled Python script given and we can't use that.\"", "%", "__title__", ")", "print", "(", "\"%s: Substituting non-compiled name: %s\"", "%", "(", "__title__", ",", "mainpyfile_noopt", ",", ")", ")", "mainpyfile", "=", "mainpyfile_noopt", "pass", "# Replace trepan's dir with script's dir in front of", "# module search path.", "sys", ".", "path", "[", "0", "]", "=", "dbg", ".", "main_dirname", "=", "osp", ".", "dirname", "(", "mainpyfile", ")", "# XXX If a signal has been received we continue in the loop, otherwise", "# the loop exits for some reason.", "dbg", ".", "sig_received", "=", "False", "# if not mainpyfile:", "# print('For now, you need to specify a Python script name!')", "# sys.exit(2)", "# pass", "while", "True", ":", "# Run the debugged script over and over again until we get it", "# right.", "try", ":", "if", "dbg", ".", "program_sys_argv", "and", "mainpyfile", ":", "normal_termination", "=", "dbg", ".", "run_script", "(", "mainpyfile", ")", "if", "not", "normal_termination", ":", "break", "else", ":", "dbg", ".", "core", ".", "execution_status", "=", "'No program'", "dbg", ".", "core", ".", "processor", ".", "process_commands", "(", ")", "pass", "dbg", ".", "core", ".", "execution_status", "=", "'Terminated'", "dbg", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "\"The program finished - quit or restart\"", ")", "dbg", ".", "core", ".", "processor", ".", "process_commands", "(", ")", "except", "Mexcept", ".", "DebuggerQuit", ":", "break", "except", "Mexcept", ".", "DebuggerRestart", ":", "dbg", ".", "core", ".", "execution_status", "=", "'Restart requested'", "if", "dbg", ".", "program_sys_argv", ":", "sys", ".", "argv", "=", "list", "(", "dbg", ".", "program_sys_argv", ")", "part1", "=", "(", "'Restarting %s with arguments:'", "%", "dbg", ".", "core", ".", "filename", "(", "mainpyfile", ")", ")", "args", "=", "' '", ".", "join", "(", "dbg", ".", "program_sys_argv", "[", "1", ":", "]", ")", "dbg", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "Mmisc", ".", "wrapped_lines", "(", "part1", ",", "args", ",", "dbg", ".", "settings", "[", "'width'", "]", ")", ")", "else", ":", "break", "except", "SystemExit", ":", "# In most cases SystemExit does not warrant a post-mortem session.", "break", "pass", "# Restore old sys.argv", "sys", ".", "argv", "=", "orig_sys_argv", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerUserOutput.open
Use this to set where to write to. output can be a file object or a string. This code raises IOError on error.
trepan/inout/output.py
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 elif isinstance(output, 'string'.__class__): # FIXME output = open(output, 'w') else: raise IOError("Invalid output type (%s) for %s" % (output.__class__.__name__, output)) # raise IOError("Invalid output type (%s) for %s" % (type(output), # output)) self.output = output return
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 elif isinstance(output, 'string'.__class__): # FIXME output = open(output, 'w') else: raise IOError("Invalid output type (%s) for %s" % (output.__class__.__name__, output)) # raise IOError("Invalid output type (%s) for %s" % (type(output), # output)) self.output = output return
[ "Use", "this", "to", "set", "where", "to", "write", "to", ".", "output", "can", "be", "a", "file", "object", "or", "a", "string", ".", "This", "code", "raises", "IOError", "on", "error", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/output.py#L37-L52
[ "def", "open", "(", "self", ",", "output", ",", "opts", "=", "None", ")", ":", "if", "isinstance", "(", "output", ",", "io", ".", "TextIOWrapper", ")", "or", "isinstance", "(", "output", ",", "io", ".", "StringIO", ")", "or", "output", "==", "sys", ".", "stdout", ":", "pass", "elif", "isinstance", "(", "output", ",", "'string'", ".", "__class__", ")", ":", "# FIXME", "output", "=", "open", "(", "output", ",", "'w'", ")", "else", ":", "raise", "IOError", "(", "\"Invalid output type (%s) for %s\"", "%", "(", "output", ".", "__class__", ".", "__name__", ",", "output", ")", ")", "# raise IOError(\"Invalid output type (%s) for %s\" % (type(output),", "# output))", "self", ".", "output", "=", "output", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerUserOutput.write
This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'.
trepan/inout/output.py
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: self.flush() return
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: self.flush() return
[ "This", "method", "the", "debugger", "uses", "to", "write", ".", "In", "contrast", "to", "writeline", "no", "newline", "is", "added", "to", "the", "end", "to", "str", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/output.py#L54-L62
[ "def", "write", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "output", ".", "closed", ":", "raise", "IOError", "(", "\"writing %s on a closed file\"", "%", "msg", ")", "self", ".", "output", ".", "write", "(", "msg", ")", "if", "self", ".", "flush_after_write", ":", "self", ".", "flush", "(", ")", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
lookup_signame
Find the corresponding signal name for 'num'. Return None if 'num' is invalid.
trepan/lib/sighandler.py
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 # Something went wrong. Should have returned above return None
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 # Something went wrong. Should have returned above return None
[ "Find", "the", "corresponding", "signal", "name", "for", "num", ".", "Return", "None", "if", "num", "is", "invalid", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L36-L46
[ "def", "lookup_signame", "(", "num", ")", ":", "signames", "=", "signal", ".", "__dict__", "num", "=", "abs", "(", "num", ")", "for", "signame", "in", "list", "(", "signames", ".", "keys", "(", ")", ")", ":", "if", "signame", ".", "startswith", "(", "'SIG'", ")", "and", "signames", "[", "signame", "]", "==", "num", ":", "return", "signame", "pass", "# Something went wrong. Should have returned above", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
lookup_signum
Find the corresponding signal number for 'name'. Return None if 'name' is invalid.
trepan/lib/sighandler.py
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 getattr(signal, uname) return None return
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 getattr(signal, uname) return None return
[ "Find", "the", "corresponding", "signal", "number", "for", "name", ".", "Return", "None", "if", "name", "is", "invalid", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L49-L60
[ "def", "lookup_signum", "(", "name", ")", ":", "uname", "=", "name", ".", "upper", "(", ")", "if", "(", "uname", ".", "startswith", "(", "'SIG'", ")", "and", "hasattr", "(", "signal", ",", "uname", ")", ")", ":", "return", "getattr", "(", "signal", ",", "uname", ")", "else", ":", "uname", "=", "\"SIG\"", "+", "uname", "if", "hasattr", "(", "signal", ",", "uname", ")", ":", "return", "getattr", "(", "signal", ",", "uname", ")", "return", "None", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
canonic_signame
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.
trepan/lib/sighandler.py
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(name_num) if signum is None: # Maybe signame is a number? try: num = int(name_num) signame = lookup_signame(num) if signame is None: return None except: return False return signame signame = name_num.upper() if not signame.startswith('SIG'): return 'SIG'+signame return signame
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(name_num) if signum is None: # Maybe signame is a number? try: num = int(name_num) signame = lookup_signame(num) if signame is None: return None except: return False return signame signame = name_num.upper() if not signame.startswith('SIG'): return 'SIG'+signame return signame
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L63-L82
[ "def", "canonic_signame", "(", "name_num", ")", ":", "signum", "=", "lookup_signum", "(", "name_num", ")", "if", "signum", "is", "None", ":", "# Maybe signame is a number?", "try", ":", "num", "=", "int", "(", "name_num", ")", "signame", "=", "lookup_signame", "(", "num", ")", "if", "signame", "is", "None", ":", "return", "None", "except", ":", "return", "False", "return", "signame", "signame", "=", "name_num", ".", "upper", "(", ")", "if", "not", "signame", ".", "startswith", "(", "'SIG'", ")", ":", "return", "'SIG'", "+", "signame", "return", "signame" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.set_signal_replacement
A replacement for signal.signal which chains the signal behind the debugger's handler
trepan/lib/sighandler.py
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" " I know about.") % signum) return False # Since the intent is to set a handler, we should pass this # signal on to the handler self.sigs[signame].pass_along = True if self.check_and_adjust_sighandler(signame, self.sigs): self.sigs[signame].old_handler = handle return True return False
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" " I know about.") % signum) return False # Since the intent is to set a handler, we should pass this # signal on to the handler self.sigs[signame].pass_along = True if self.check_and_adjust_sighandler(signame, self.sigs): self.sigs[signame].old_handler = handle return True return False
[ "A", "replacement", "for", "signal", ".", "signal", "which", "chains", "the", "signal", "behind", "the", "debugger", "s", "handler" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L221-L235
[ "def", "set_signal_replacement", "(", "self", ",", "signum", ",", "handle", ")", ":", "signame", "=", "lookup_signame", "(", "signum", ")", "if", "signame", "is", "None", ":", "self", ".", "dbgr", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "(", "\"%s is not a signal number\"", "\" I know about.\"", ")", "%", "signum", ")", "return", "False", "# Since the intent is to set a handler, we should pass this", "# signal on to the handler", "self", ".", "sigs", "[", "signame", "]", ".", "pass_along", "=", "True", "if", "self", ".", "check_and_adjust_sighandler", "(", "signame", ",", "self", ".", "sigs", ")", ":", "self", ".", "sigs", "[", "signame", "]", ".", "old_handler", "=", "handle", "return", "True", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.check_and_adjust_sighandler
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.
trepan/lib/sighandler.py
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 None if error or not found. """ signum = lookup_signum(signame) try: old_handler = signal.getsignal(signum) except ValueError: # On some OS's (Redhat 8), SIGNUM's are listed (like # SIGRTMAX) that getsignal can't handle. if signame in self.sigs: sigs.pop(signame) pass return None if old_handler != self.sigs[signame].handle: if old_handler not in [signal.SIG_IGN, signal.SIG_DFL]: # save the program's signal handler sigs[signame].old_handler = old_handler pass # set/restore _our_ signal handler try: # signal.signal(signum, self.sigs[signame].handle) self._orig_set_signal(signum, self.sigs[signame].handle) except ValueError: # Probably not in main thread return False except KeyError: # May be weird keys from 3.3 return False pass return True
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 None if error or not found. """ signum = lookup_signum(signame) try: old_handler = signal.getsignal(signum) except ValueError: # On some OS's (Redhat 8), SIGNUM's are listed (like # SIGRTMAX) that getsignal can't handle. if signame in self.sigs: sigs.pop(signame) pass return None if old_handler != self.sigs[signame].handle: if old_handler not in [signal.SIG_IGN, signal.SIG_DFL]: # save the program's signal handler sigs[signame].old_handler = old_handler pass # set/restore _our_ signal handler try: # signal.signal(signum, self.sigs[signame].handle) self._orig_set_signal(signum, self.sigs[signame].handle) except ValueError: # Probably not in main thread return False except KeyError: # May be weird keys from 3.3 return False pass return True
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L237-L273
[ "def", "check_and_adjust_sighandler", "(", "self", ",", "signame", ",", "sigs", ")", ":", "signum", "=", "lookup_signum", "(", "signame", ")", "try", ":", "old_handler", "=", "signal", ".", "getsignal", "(", "signum", ")", "except", "ValueError", ":", "# On some OS's (Redhat 8), SIGNUM's are listed (like", "# SIGRTMAX) that getsignal can't handle.", "if", "signame", "in", "self", ".", "sigs", ":", "sigs", ".", "pop", "(", "signame", ")", "pass", "return", "None", "if", "old_handler", "!=", "self", ".", "sigs", "[", "signame", "]", ".", "handle", ":", "if", "old_handler", "not", "in", "[", "signal", ".", "SIG_IGN", ",", "signal", ".", "SIG_DFL", "]", ":", "# save the program's signal handler", "sigs", "[", "signame", "]", ".", "old_handler", "=", "old_handler", "pass", "# set/restore _our_ signal handler", "try", ":", "# signal.signal(signum, self.sigs[signame].handle)", "self", ".", "_orig_set_signal", "(", "signum", ",", "self", ".", "sigs", "[", "signame", "]", ".", "handle", ")", "except", "ValueError", ":", "# Probably not in main thread", "return", "False", "except", "KeyError", ":", "# May be weird keys from 3.3", "return", "False", "pass", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.check_and_adjust_sighandlers
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.
trepan/lib/sighandler.py
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): break pass return
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): break pass return
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L275-L282
[ "def", "check_and_adjust_sighandlers", "(", "self", ")", ":", "for", "signame", "in", "list", "(", "self", ".", "sigs", ".", "keys", "(", ")", ")", ":", "if", "not", "self", ".", "check_and_adjust_sighandler", "(", "signame", ",", "self", ".", "sigs", ")", ":", "break", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.print_info_signal_entry
Print status for a single signal name (signame)
trepan/lib/sighandler.py
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()): # Fake up an entry as though signame were in sigs. self.dbgr.intf[-1].msg(self.info_fmt % (signame, 'No', 'No', 'No', 'Yes', description)) return sig_obj = self.sigs[signame] self.dbgr.intf[-1].msg(self.info_fmt % (signame, YN(sig_obj.b_stop), YN(sig_obj.print_method is not None), YN(sig_obj.print_stack), YN(sig_obj.pass_along), description)) return
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()): # Fake up an entry as though signame were in sigs. self.dbgr.intf[-1].msg(self.info_fmt % (signame, 'No', 'No', 'No', 'Yes', description)) return sig_obj = self.sigs[signame] self.dbgr.intf[-1].msg(self.info_fmt % (signame, YN(sig_obj.b_stop), YN(sig_obj.print_method is not None), YN(sig_obj.print_stack), YN(sig_obj.pass_along), description)) return
[ "Print", "status", "for", "a", "single", "signal", "name", "(", "signame", ")" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L296-L318
[ "def", "print_info_signal_entry", "(", "self", ",", "signame", ")", ":", "if", "signame", "in", "signal_description", ":", "description", "=", "signal_description", "[", "signame", "]", "else", ":", "description", "=", "\"\"", "pass", "if", "signame", "not", "in", "list", "(", "self", ".", "sigs", ".", "keys", "(", ")", ")", ":", "# Fake up an entry as though signame were in sigs.", "self", ".", "dbgr", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "self", ".", "info_fmt", "%", "(", "signame", ",", "'No'", ",", "'No'", ",", "'No'", ",", "'Yes'", ",", "description", ")", ")", "return", "sig_obj", "=", "self", ".", "sigs", "[", "signame", "]", "self", ".", "dbgr", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "self", ".", "info_fmt", "%", "(", "signame", ",", "YN", "(", "sig_obj", ".", "b_stop", ")", ",", "YN", "(", "sig_obj", ".", "print_method", "is", "not", "None", ")", ",", "YN", "(", "sig_obj", ".", "print_stack", ")", ",", "YN", "(", "sig_obj", ".", "pass_along", ")", ",", "description", ")", ")", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.info_signal
Print information about a signal
trepan/lib/sighandler.py
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 self.dbgr.core.processor.section(self.header) for signame in self.siglist: self.print_info_signal_entry(signame) return True else: signame = args[1] pass pass signame = self.is_name_or_number(signame) self.dbgr.core.processor.section(self.header) self.print_info_signal_entry(signame) return True
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 self.dbgr.core.processor.section(self.header) for signame in self.siglist: self.print_info_signal_entry(signame) return True else: signame = args[1] pass pass signame = self.is_name_or_number(signame) self.dbgr.core.processor.section(self.header) self.print_info_signal_entry(signame) return True
[ "Print", "information", "about", "a", "signal" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L320-L340
[ "def", "info_signal", "(", "self", ",", "args", ")", ":", "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", "self", ".", "dbgr", ".", "core", ".", "processor", ".", "section", "(", "self", ".", "header", ")", "for", "signame", "in", "self", ".", "siglist", ":", "self", ".", "print_info_signal_entry", "(", "signame", ")", "return", "True", "else", ":", "signame", "=", "args", "[", "1", "]", "pass", "pass", "signame", "=", "self", ".", "is_name_or_number", "(", "signame", ")", "self", ".", "dbgr", ".", "core", ".", "processor", ".", "section", "(", "self", ".", "header", ")", "self", ".", "print_info_signal_entry", "(", "signame", ")", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.action
Delegate the actions specified in 'arg' to another method.
trepan/lib/sighandler.py
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 signame: return if len(args) == 1: self.info_signal([signame]) return True # We can display information about 'fatal' signals, but not # change their actions. if signame in fatal_signals: return None if signame not in list(self.sigs.keys()): if not self.initialize_handler(signame): return None pass # multiple commands might be specified, i.e. 'nopass nostop' for attr in args[1:]: if attr.startswith('no'): on = False attr = attr[2:] else: on = True if 'stop'.startswith(attr): self.handle_stop(signame, on) elif 'print'.startswith(attr) and len(attr) >= 2: self.handle_print(signame, on) elif 'pass'.startswith(attr): self.handle_pass(signame, on) elif 'ignore'.startswith(attr): self.handle_ignore(signame, on) elif 'stack'.startswith(attr): self.handle_print_stack(signame, on) else: self.dbgr.intf[-1].errmsg('Invalid arguments') pass pass return self.check_and_adjust_sighandler(signame, self.sigs)
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 signame: return if len(args) == 1: self.info_signal([signame]) return True # We can display information about 'fatal' signals, but not # change their actions. if signame in fatal_signals: return None if signame not in list(self.sigs.keys()): if not self.initialize_handler(signame): return None pass # multiple commands might be specified, i.e. 'nopass nostop' for attr in args[1:]: if attr.startswith('no'): on = False attr = attr[2:] else: on = True if 'stop'.startswith(attr): self.handle_stop(signame, on) elif 'print'.startswith(attr) and len(attr) >= 2: self.handle_print(signame, on) elif 'pass'.startswith(attr): self.handle_pass(signame, on) elif 'ignore'.startswith(attr): self.handle_ignore(signame, on) elif 'stack'.startswith(attr): self.handle_print_stack(signame, on) else: self.dbgr.intf[-1].errmsg('Invalid arguments') pass pass return self.check_and_adjust_sighandler(signame, self.sigs)
[ "Delegate", "the", "actions", "specified", "in", "arg", "to", "another", "method", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L342-L387
[ "def", "action", "(", "self", ",", "arg", ")", ":", "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", "signame", ":", "return", "if", "len", "(", "args", ")", "==", "1", ":", "self", ".", "info_signal", "(", "[", "signame", "]", ")", "return", "True", "# We can display information about 'fatal' signals, but not", "# change their actions.", "if", "signame", "in", "fatal_signals", ":", "return", "None", "if", "signame", "not", "in", "list", "(", "self", ".", "sigs", ".", "keys", "(", ")", ")", ":", "if", "not", "self", ".", "initialize_handler", "(", "signame", ")", ":", "return", "None", "pass", "# multiple commands might be specified, i.e. 'nopass nostop'", "for", "attr", "in", "args", "[", "1", ":", "]", ":", "if", "attr", ".", "startswith", "(", "'no'", ")", ":", "on", "=", "False", "attr", "=", "attr", "[", "2", ":", "]", "else", ":", "on", "=", "True", "if", "'stop'", ".", "startswith", "(", "attr", ")", ":", "self", ".", "handle_stop", "(", "signame", ",", "on", ")", "elif", "'print'", ".", "startswith", "(", "attr", ")", "and", "len", "(", "attr", ")", ">=", "2", ":", "self", ".", "handle_print", "(", "signame", ",", "on", ")", "elif", "'pass'", ".", "startswith", "(", "attr", ")", ":", "self", ".", "handle_pass", "(", "signame", ",", "on", ")", "elif", "'ignore'", ".", "startswith", "(", "attr", ")", ":", "self", ".", "handle_ignore", "(", "signame", ",", "on", ")", "elif", "'stack'", ".", "startswith", "(", "attr", ")", ":", "self", ".", "handle_print_stack", "(", "signame", ",", "on", ")", "else", ":", "self", ".", "dbgr", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "'Invalid arguments'", ")", "pass", "pass", "return", "self", ".", "check_and_adjust_sighandler", "(", "signame", ",", "self", ".", "sigs", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.handle_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.
trepan/lib/sighandler.py
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
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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L389-L394
[ "def", "handle_print_stack", "(", "self", ",", "signame", ",", "print_stack", ")", ":", "self", ".", "sigs", "[", "signame", "]", ".", "print_stack", "=", "print_stack", "return", "print_stack" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.handle_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.
trepan/lib/sighandler.py
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 nopass self.sigs[signame].print_method = self.dbgr.intf[-1].msg self.sigs[signame].pass_along = False else: self.sigs[signame].b_stop = False pass return set_stop
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 nopass self.sigs[signame].print_method = self.dbgr.intf[-1].msg self.sigs[signame].pass_along = False else: self.sigs[signame].b_stop = False pass return 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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L396-L408
[ "def", "handle_stop", "(", "self", ",", "signame", ",", "set_stop", ")", ":", "if", "set_stop", ":", "self", ".", "sigs", "[", "signame", "]", ".", "b_stop", "=", "True", "# stop keyword implies print AND nopass", "self", ".", "sigs", "[", "signame", "]", ".", "print_method", "=", "self", ".", "dbgr", ".", "intf", "[", "-", "1", "]", ".", "msg", "self", ".", "sigs", "[", "signame", "]", ".", "pass_along", "=", "False", "else", ":", "self", ".", "sigs", "[", "signame", "]", ".", "b_stop", "=", "False", "pass", "return", "set_stop" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.handle_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.
trepan/lib/sighandler.py
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: # Pass implies nostop self.sigs[signame].b_stop = False pass return set_pass
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: # Pass implies nostop self.sigs[signame].b_stop = False pass return 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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L410-L420
[ "def", "handle_pass", "(", "self", ",", "signame", ",", "set_pass", ")", ":", "self", ".", "sigs", "[", "signame", "]", ".", "pass_along", "=", "set_pass", "if", "set_pass", ":", "# Pass implies nostop", "self", ".", "sigs", "[", "signame", "]", ".", "b_stop", "=", "False", "pass", "return", "set_pass" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SignalManager.handle_print
Set whether we print or not when this signal is caught.
trepan/lib/sighandler.py
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
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
[ "Set", "whether", "we", "print", "or", "not", "when", "this", "signal", "is", "caught", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L428-L435
[ "def", "handle_print", "(", "self", ",", "signame", ",", "set_print", ")", ":", "if", "set_print", ":", "self", ".", "sigs", "[", "signame", "]", ".", "print_method", "=", "self", ".", "dbgr", ".", "intf", "[", "-", "1", "]", ".", "msg", "else", ":", "self", ".", "sigs", "[", "signame", "]", ".", "print_method", "=", "None", "pass", "return", "set_print" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
SigHandler.handle
This method is called when a signal is received.
trepan/lib/sighandler.py
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 = traceback.format_stack(frame) for s in strings: if s[-1] == '\n': s = s[0:-1] self.print_method(s) pass pass if self.b_stop: core = self.dbgr.core old_trace_hook_suspend = core.trace_hook_suspend core.trace_hook_suspend = True core.stop_reason = ('intercepting signal %s (%d)' % (self.signame, signum)) core.processor.event_processor(frame, 'signal', signum) core.trace_hook_suspend = old_trace_hook_suspend pass if self.pass_along: # pass the signal to the program if self.old_handler: self.old_handler(signum, frame) pass pass return
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 = traceback.format_stack(frame) for s in strings: if s[-1] == '\n': s = s[0:-1] self.print_method(s) pass pass if self.b_stop: core = self.dbgr.core old_trace_hook_suspend = core.trace_hook_suspend core.trace_hook_suspend = True core.stop_reason = ('intercepting signal %s (%d)' % (self.signame, signum)) core.processor.event_processor(frame, 'signal', signum) core.trace_hook_suspend = old_trace_hook_suspend pass if self.pass_along: # pass the signal to the program if self.old_handler: self.old_handler(signum, frame) pass pass return
[ "This", "method", "is", "called", "when", "a", "signal", "is", "received", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/sighandler.py#L466-L494
[ "def", "handle", "(", "self", ",", "signum", ",", "frame", ")", ":", "if", "self", ".", "print_method", ":", "self", ".", "print_method", "(", "'\\nProgram received signal %s.'", "%", "self", ".", "signame", ")", "if", "self", ".", "print_stack", ":", "import", "traceback", "strings", "=", "traceback", ".", "format_stack", "(", "frame", ")", "for", "s", "in", "strings", ":", "if", "s", "[", "-", "1", "]", "==", "'\\n'", ":", "s", "=", "s", "[", "0", ":", "-", "1", "]", "self", ".", "print_method", "(", "s", ")", "pass", "pass", "if", "self", ".", "b_stop", ":", "core", "=", "self", ".", "dbgr", ".", "core", "old_trace_hook_suspend", "=", "core", ".", "trace_hook_suspend", "core", ".", "trace_hook_suspend", "=", "True", "core", ".", "stop_reason", "=", "(", "'intercepting signal %s (%d)'", "%", "(", "self", ".", "signame", ",", "signum", ")", ")", "core", ".", "processor", ".", "event_processor", "(", "frame", ",", "'signal'", ",", "signum", ")", "core", ".", "trace_hook_suspend", "=", "old_trace_hook_suspend", "pass", "if", "self", ".", "pass_along", ":", "# pass the signal to the program", "if", "self", ".", "old_handler", ":", "self", ".", "old_handler", "(", "signum", ",", "frame", ")", "pass", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
is_ok_line_for_breakpoint
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.
trepan/clifns.py
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 line: errmsg_fn('End of file') return False line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): errmsg_fn('Blank or comment') return False return True
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 line: errmsg_fn('End of file') return False line = line.strip() # Don't allow setting breakpoint at a blank line if (not line or (line[0] == '#') or (line[:3] == '"""') or line[:3] == "'''"): errmsg_fn('Blank or comment') return False return True
[ "Check", "whether", "specified", "line", "seems", "to", "be", "executable", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/clifns.py#L21-L37
[ "def", "is_ok_line_for_breakpoint", "(", "filename", ",", "lineno", ",", "errmsg_fn", ")", ":", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ")", "if", "not", "line", ":", "errmsg_fn", "(", "'End of file'", ")", "return", "False", "line", "=", "line", ".", "strip", "(", ")", "# Don't allow setting breakpoint at a blank line", "if", "(", "not", "line", "or", "(", "line", "[", "0", "]", "==", "'#'", ")", "or", "(", "line", "[", ":", "3", "]", "==", "'\"\"\"'", ")", "or", "line", "[", ":", "3", "]", "==", "\"'''\"", ")", ":", "errmsg_fn", "(", "'Blank or comment'", ")", "return", "False", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
file2module
Given a file name, extract the most likely module name.
trepan/clifns.py
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
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
[ "Given", "a", "file", "name", "extract", "the", "most", "likely", "module", "name", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/clifns.py#L40-L48
[ "def", "file2module", "(", "filename", ")", ":", "basename", "=", "osp", ".", "basename", "(", "filename", ")", "if", "'.'", "in", "basename", ":", "pos", "=", "basename", ".", "rfind", "(", "'.'", ")", "return", "basename", "[", ":", "pos", "]", "else", ":", "return", "basename", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
search_file
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
trepan/clifns.py
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='.' elif trydir == '$cdir': trydir = cdir tryfile = osp.realpath(osp.join(trydir, filename)) if osp.isfile(tryfile): return tryfile 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='.' elif trydir == '$cdir': trydir = cdir tryfile = osp.realpath(osp.join(trydir, filename)) if osp.isfile(tryfile): return tryfile 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" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/clifns.py#L51-L65
[ "def", "search_file", "(", "filename", ",", "directories", ",", "cdir", ")", ":", "for", "trydir", "in", "directories", ":", "# Handle $cwd and $cdir", "if", "trydir", "==", "'$cwd'", ":", "trydir", "=", "'.'", "elif", "trydir", "==", "'$cdir'", ":", "trydir", "=", "cdir", "tryfile", "=", "osp", ".", "realpath", "(", "osp", ".", "join", "(", "trydir", ",", "filename", ")", ")", "if", "osp", ".", "isfile", "(", "tryfile", ")", ":", "return", "tryfile", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
whence_file
Do a shell-like path lookup for py_script and return the results. If we can't find anything return py_script
trepan/clifns.py
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: dirnames = os.environ['PATH'].split(os.pathsep) for dirname in dirnames: py_script_try = osp.join(dirname, py_script) if osp.exists(py_script_try): return py_script_try # Failure 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: dirnames = os.environ['PATH'].split(os.pathsep) for dirname in dirnames: py_script_try = osp.join(dirname, py_script) if osp.exists(py_script_try): return py_script_try # Failure return py_script
[ "Do", "a", "shell", "-", "like", "path", "lookup", "for", "py_script", "and", "return", "the", "results", ".", "If", "we", "can", "t", "find", "anything", "return", "py_script" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/clifns.py#L68-L81
[ "def", "whence_file", "(", "py_script", ",", "dirnames", "=", "None", ")", ":", "if", "py_script", ".", "find", "(", "os", ".", "sep", ")", "!=", "-", "1", ":", "# Don't search since this name has path separator components", "return", "py_script", "if", "dirnames", "is", "None", ":", "dirnames", "=", "os", ".", "environ", "[", "'PATH'", "]", ".", "split", "(", "os", ".", "pathsep", ")", "for", "dirname", "in", "dirnames", ":", "py_script_try", "=", "osp", ".", "join", "(", "dirname", ",", "py_script", ")", "if", "osp", ".", "exists", "(", "py_script_try", ")", ":", "return", "py_script_try", "# Failure", "return", "py_script" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
print_obj
Return a string representation of an object
trepan/lib/printing.py
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_globals, frame.f_locals) pass except: return 'No symbol "' + arg + '" in current context.' # format and print what = arg if format: what = format + ' ' + arg obj = printf(obj, format) s = '%s = %s' % (what, obj) if not short: s += '\ntype = %s' % type(obj) if callable(obj): argspec = print_argspec(obj, arg) if argspec: s += ':\n\t' if inspect.isclass(obj): s += 'Class constructor information:\n\t' obj = obj.__init__ elif isinstance(obj, types.InstanceType): obj = obj.__call__ pass s+= argspec pass # Try to list the members of a class. # Not sure if this is correct or the # best way to do. s = print_dict(s, obj, "object variables") if hasattr(obj, "__class__"): s = print_dict(s, obj.__class__, "class variables") pass return s
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_globals, frame.f_locals) pass except: return 'No symbol "' + arg + '" in current context.' # format and print what = arg if format: what = format + ' ' + arg obj = printf(obj, format) s = '%s = %s' % (what, obj) if not short: s += '\ntype = %s' % type(obj) if callable(obj): argspec = print_argspec(obj, arg) if argspec: s += ':\n\t' if inspect.isclass(obj): s += 'Class constructor information:\n\t' obj = obj.__init__ elif isinstance(obj, types.InstanceType): obj = obj.__call__ pass s+= argspec pass # Try to list the members of a class. # Not sure if this is correct or the # best way to do. s = print_dict(s, obj, "object variables") if hasattr(obj, "__class__"): s = print_dict(s, obj.__class__, "class variables") pass return s
[ "Return", "a", "string", "representation", "of", "an", "object" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/printing.py#L44-L84
[ "def", "print_obj", "(", "arg", ",", "frame", ",", "format", "=", "None", ",", "short", "=", "False", ")", ":", "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_globals", ",", "frame", ".", "f_locals", ")", "pass", "except", ":", "return", "'No symbol \"'", "+", "arg", "+", "'\" in current context.'", "# format and print", "what", "=", "arg", "if", "format", ":", "what", "=", "format", "+", "' '", "+", "arg", "obj", "=", "printf", "(", "obj", ",", "format", ")", "s", "=", "'%s = %s'", "%", "(", "what", ",", "obj", ")", "if", "not", "short", ":", "s", "+=", "'\\ntype = %s'", "%", "type", "(", "obj", ")", "if", "callable", "(", "obj", ")", ":", "argspec", "=", "print_argspec", "(", "obj", ",", "arg", ")", "if", "argspec", ":", "s", "+=", "':\\n\\t'", "if", "inspect", ".", "isclass", "(", "obj", ")", ":", "s", "+=", "'Class constructor information:\\n\\t'", "obj", "=", "obj", ".", "__init__", "elif", "isinstance", "(", "obj", ",", "types", ".", "InstanceType", ")", ":", "obj", "=", "obj", ".", "__call__", "pass", "s", "+=", "argspec", "pass", "# Try to list the members of a class.", "# Not sure if this is correct or the", "# best way to do.", "s", "=", "print_dict", "(", "s", ",", "obj", ",", "\"object variables\"", ")", "if", "hasattr", "(", "obj", ",", "\"__class__\"", ")", ":", "s", "=", "print_dict", "(", "s", ",", "obj", ".", "__class__", ",", "\"class variables\"", ")", "pass", "return", "s" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
pyfiles
All python files caller's dir without the path and trailing .py
trepan/misc.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.join(d, '[a-zA-Z]*.py')) return [ os.path.basename(filename[0:-3]) for filename in py_files ]
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.join(d, '[a-zA-Z]*.py')) return [ os.path.basename(filename[0:-3]) for filename in py_files ]
[ "All", "python", "files", "caller", "s", "dir", "without", "the", "path", "and", "trailing", ".", "py" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/misc.py#L42-L49
[ "def", "pyfiles", "(", "callername", ",", "level", "=", "2", ")", ":", "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", ".", "join", "(", "d", ",", "'[a-zA-Z]*.py'", ")", ")", "return", "[", "os", ".", "path", ".", "basename", "(", "filename", "[", "0", ":", "-", "3", "]", ")", "for", "filename", "in", "py_files", "]" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BWProcessor.adjust_frame
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.
trepan/bwprocessor/main.py
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.") return # Below we remove any negativity. At the end, pos will be # the new value of self.curindex. if absolute_pos: if pos >= 0: pos = len(self.stack)-pos-1 else: pos = -pos-1 else: pos += self.curindex if pos < 0: Mmsg.errmsg(self, "Adjusting would put us beyond the oldest frame.") return elif pos >= len(self.stack): Mmsg.errmsg(self, "Adjusting would put us beyond the newest frame.") return self.curindex = pos self.curframe = self.stack[self.curindex][0] self.print_location() self.list_lineno = None return
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.") return # Below we remove any negativity. At the end, pos will be # the new value of self.curindex. if absolute_pos: if pos >= 0: pos = len(self.stack)-pos-1 else: pos = -pos-1 else: pos += self.curindex if pos < 0: Mmsg.errmsg(self, "Adjusting would put us beyond the oldest frame.") return elif pos >= len(self.stack): Mmsg.errmsg(self, "Adjusting would put us beyond the newest frame.") return self.curindex = pos self.curframe = self.stack[self.curindex][0] self.print_location() self.list_lineno = None return
[ "Adjust", "stack", "frame", "by", "pos", "positions", ".", "If", "absolute_pos", "then", "pos", "is", "an", "absolute", "number", ".", "Otherwise", "it", "is", "a", "relative", "number", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L141-L173
[ "def", "adjust_frame", "(", "self", ",", "pos", ",", "absolute_pos", ")", ":", "if", "not", "self", ".", "curframe", ":", "Mmsg", ".", "errmsg", "(", "self", ",", "\"No stack.\"", ")", "return", "# Below we remove any negativity. At the end, pos will be", "# the new value of self.curindex.", "if", "absolute_pos", ":", "if", "pos", ">=", "0", ":", "pos", "=", "len", "(", "self", ".", "stack", ")", "-", "pos", "-", "1", "else", ":", "pos", "=", "-", "pos", "-", "1", "else", ":", "pos", "+=", "self", ".", "curindex", "if", "pos", "<", "0", ":", "Mmsg", ".", "errmsg", "(", "self", ",", "\"Adjusting would put us beyond the oldest frame.\"", ")", "return", "elif", "pos", ">=", "len", "(", "self", ".", "stack", ")", ":", "Mmsg", ".", "errmsg", "(", "self", ",", "\"Adjusting would put us beyond the newest frame.\"", ")", "return", "self", ".", "curindex", "=", "pos", "self", ".", "curframe", "=", "self", ".", "stack", "[", "self", ".", "curindex", "]", "[", "0", "]", "self", ".", "print_location", "(", ")", "self", ".", "list_lineno", "=", "None", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BWProcessor.ok_for_running
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.
trepan/bwprocessor/main.py
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'): if not (self.core.execution_status in cmd_obj.execution_set): part1 = ("Command '%s' is not available for execution " "status:" % name) Mmsg.errmsg(self, Mmisc. wrapped_lines(part1, self.core.execution_status, self.debugger.settings['width'])) return False pass if self.frame is None and cmd_obj.need_stack: self.intf[-1].errmsg("Command '%s' needs an execution stack." % name) return False return True
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'): if not (self.core.execution_status in cmd_obj.execution_set): part1 = ("Command '%s' is not available for execution " "status:" % name) Mmsg.errmsg(self, Mmisc. wrapped_lines(part1, self.core.execution_status, self.debugger.settings['width'])) return False pass if self.frame is None and cmd_obj.need_stack: self.intf[-1].errmsg("Command '%s' needs an execution stack." % name) return False return True
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L259-L279
[ "def", "ok_for_running", "(", "self", ",", "cmd_obj", ",", "name", ",", "cmd_hash", ")", ":", "if", "hasattr", "(", "cmd_obj", ",", "'execution_set'", ")", ":", "if", "not", "(", "self", ".", "core", ".", "execution_status", "in", "cmd_obj", ".", "execution_set", ")", ":", "part1", "=", "(", "\"Command '%s' is not available for execution \"", "\"status:\"", "%", "name", ")", "Mmsg", ".", "errmsg", "(", "self", ",", "Mmisc", ".", "wrapped_lines", "(", "part1", ",", "self", ".", "core", ".", "execution_status", ",", "self", ".", "debugger", ".", "settings", "[", "'width'", "]", ")", ")", "return", "False", "pass", "if", "self", ".", "frame", "is", "None", "and", "cmd_obj", ".", "need_stack", ":", "self", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "\"Command '%s' needs an execution stack.\"", "%", "name", ")", "return", "False", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BWProcessor.setup
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.
trepan/bwprocessor/main.py
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() if self.settings('dbg_trepan'): self.frame = inspect.currentframe() pass if self.event in ['exception', 'c_exception']: exc_type, exc_value, exc_traceback = self.event_arg else: _, _, exc_traceback = (None, None, None,) # NOQA pass if self.frame or exc_traceback: self.stack, self.curindex = \ get_stack(self.frame, exc_traceback, None, self) self.curframe = self.stack[self.curindex][0] self.thread_name = Mthread.current_thread_name() else: self.stack = self.curframe = \ self.botframe = None pass if self.curframe: self.list_lineno = \ max(1, inspect.getlineno(self.curframe)) else: self.list_lineno = None pass # if self.execRcLines()==1: return True return False
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() if self.settings('dbg_trepan'): self.frame = inspect.currentframe() pass if self.event in ['exception', 'c_exception']: exc_type, exc_value, exc_traceback = self.event_arg else: _, _, exc_traceback = (None, None, None,) # NOQA pass if self.frame or exc_traceback: self.stack, self.curindex = \ get_stack(self.frame, exc_traceback, None, self) self.curframe = self.stack[self.curindex][0] self.thread_name = Mthread.current_thread_name() else: self.stack = self.curframe = \ self.botframe = None pass if self.curframe: self.list_lineno = \ max(1, inspect.getlineno(self.curframe)) else: self.list_lineno = None pass # if self.execRcLines()==1: return True return False
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L370-L403
[ "def", "setup", "(", "self", ")", ":", "self", ".", "forget", "(", ")", "if", "self", ".", "settings", "(", "'dbg_trepan'", ")", ":", "self", ".", "frame", "=", "inspect", ".", "currentframe", "(", ")", "pass", "if", "self", ".", "event", "in", "[", "'exception'", ",", "'c_exception'", "]", ":", "exc_type", ",", "exc_value", ",", "exc_traceback", "=", "self", ".", "event_arg", "else", ":", "_", ",", "_", ",", "exc_traceback", "=", "(", "None", ",", "None", ",", "None", ",", ")", "# NOQA", "pass", "if", "self", ".", "frame", "or", "exc_traceback", ":", "self", ".", "stack", ",", "self", ".", "curindex", "=", "get_stack", "(", "self", ".", "frame", ",", "exc_traceback", ",", "None", ",", "self", ")", "self", ".", "curframe", "=", "self", ".", "stack", "[", "self", ".", "curindex", "]", "[", "0", "]", "self", ".", "thread_name", "=", "Mthread", ".", "current_thread_name", "(", ")", "else", ":", "self", ".", "stack", "=", "self", ".", "curframe", "=", "self", ".", "botframe", "=", "None", "pass", "if", "self", ".", "curframe", ":", "self", ".", "list_lineno", "=", "max", "(", "1", ",", "inspect", ".", "getlineno", "(", "self", ".", "curframe", ")", ")", "else", ":", "self", ".", "list_lineno", "=", "None", "pass", "# if self.execRcLines()==1: return True", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BWProcessor._populate_commands
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 class. The set of DebuggerCommand class instances form set of possible debugger commands.
trepan/bwprocessor/main.py
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 inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" cmd_instances = [] from trepan.bwprocessor import command as Mcommand eval_cmd_template = 'command_mod.%s(self)' for mod_name in Mcommand.__modules__: import_name = "command." + mod_name try: command_mod = getattr(__import__(import_name), mod_name) except: print('Error importing %s: %s' % (mod_name, sys.exc_info()[0])) continue classnames = [ tup[0] for tup in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != tup[0] and tup[0].endswith('Command')) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) cmd_instances.append(instance) except: print('Error loading %s from %s: %s' % (classname, mod_name, sys.exc_info()[0])) pass pass pass return cmd_instances
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 inside those files and for each class name, we will create an instance of that class. The set of DebuggerCommand class instances form set of possible debugger commands.""" cmd_instances = [] from trepan.bwprocessor import command as Mcommand eval_cmd_template = 'command_mod.%s(self)' for mod_name in Mcommand.__modules__: import_name = "command." + mod_name try: command_mod = getattr(__import__(import_name), mod_name) except: print('Error importing %s: %s' % (mod_name, sys.exc_info()[0])) continue classnames = [ tup[0] for tup in inspect.getmembers(command_mod, inspect.isclass) if ('DebuggerCommand' != tup[0] and tup[0].endswith('Command')) ] for classname in classnames: eval_cmd = eval_cmd_template % classname try: instance = eval(eval_cmd) cmd_instances.append(instance) except: print('Error loading %s from %s: %s' % (classname, mod_name, sys.exc_info()[0])) pass pass pass return cmd_instances
[ "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", "class", ".", "The", "set", "of", "DebuggerCommand", "class", "instances", "form", "set", "of", "possible", "debugger", "commands", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L410-L445
[ "def", "_populate_commands", "(", "self", ")", ":", "cmd_instances", "=", "[", "]", "from", "trepan", ".", "bwprocessor", "import", "command", "as", "Mcommand", "eval_cmd_template", "=", "'command_mod.%s(self)'", "for", "mod_name", "in", "Mcommand", ".", "__modules__", ":", "import_name", "=", "\"command.\"", "+", "mod_name", "try", ":", "command_mod", "=", "getattr", "(", "__import__", "(", "import_name", ")", ",", "mod_name", ")", "except", ":", "print", "(", "'Error importing %s: %s'", "%", "(", "mod_name", ",", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", ")", "continue", "classnames", "=", "[", "tup", "[", "0", "]", "for", "tup", "in", "inspect", ".", "getmembers", "(", "command_mod", ",", "inspect", ".", "isclass", ")", "if", "(", "'DebuggerCommand'", "!=", "tup", "[", "0", "]", "and", "tup", "[", "0", "]", ".", "endswith", "(", "'Command'", ")", ")", "]", "for", "classname", "in", "classnames", ":", "eval_cmd", "=", "eval_cmd_template", "%", "classname", "try", ":", "instance", "=", "eval", "(", "eval_cmd", ")", "cmd_instances", ".", "append", "(", "instance", ")", "except", ":", "print", "(", "'Error loading %s from %s: %s'", "%", "(", "classname", ",", "mod_name", ",", "sys", ".", "exc_info", "(", ")", "[", "0", "]", ")", ")", "pass", "pass", "pass", "return", "cmd_instances" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BWProcessor._populate_cmd_lists
Populate self.commands
trepan/bwprocessor/main.py
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
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
[ "Populate", "self", ".", "commands" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/main.py#L447-L454
[ "def", "_populate_cmd_lists", "(", "self", ")", ":", "self", ".", "commands", "=", "{", "}", "for", "cmd_instance", "in", "self", ".", "cmd_instances", ":", "cmd_name", "=", "cmd_instance", ".", "name", "self", ".", "commands", "[", "cmd_name", "]", "=", "cmd_instance", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
format_location
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.
trepan/bwprocessor/location.py
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 False location = {} core_obj = proc_obj.core dbgr_obj = proc_obj.debugger # Evaluation routines like "exec" don't show useful location # info. In these cases, we will use the position before that in # the stack. Hence the looping below which in practices loops # once and sometimes twice. while i_stack >= 0: frame_lineno = proc_obj.stack[i_stack] i_stack -= 1 frame, lineno = frame_lineno filename = Mstack.frame2file(core_obj, frame) location['filename'] = filename location['fn_name'] = frame.f_code.co_name location['lineno'] = lineno if '<string>' == filename and dbgr_obj.eval_string: filename = pyficache.unmap_file(filename) if '<string>' == filename: fd = tempfile.NamedTemporaryFile(suffix='.py', prefix='eval_string', delete=False) fd.write(bytes(dbgr_obj.eval_string, 'UTF-8')) fd.close() pyficache.remap_file(fd.name, '<string>') filename = fd.name pass pass opts = { 'reload_on_change' : proc_obj.settings('reload'), 'output' : 'plain' } line = pyficache.getline(filename, lineno, opts) if not line: line = linecache.getline(filename, lineno, proc_obj.curframe.f_globals) pass if line and len(line.strip()) != 0: location['text'] = line pass if '<string>' != filename: break pass return location
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 False location = {} core_obj = proc_obj.core dbgr_obj = proc_obj.debugger # Evaluation routines like "exec" don't show useful location # info. In these cases, we will use the position before that in # the stack. Hence the looping below which in practices loops # once and sometimes twice. while i_stack >= 0: frame_lineno = proc_obj.stack[i_stack] i_stack -= 1 frame, lineno = frame_lineno filename = Mstack.frame2file(core_obj, frame) location['filename'] = filename location['fn_name'] = frame.f_code.co_name location['lineno'] = lineno if '<string>' == filename and dbgr_obj.eval_string: filename = pyficache.unmap_file(filename) if '<string>' == filename: fd = tempfile.NamedTemporaryFile(suffix='.py', prefix='eval_string', delete=False) fd.write(bytes(dbgr_obj.eval_string, 'UTF-8')) fd.close() pyficache.remap_file(fd.name, '<string>') filename = fd.name pass pass opts = { 'reload_on_change' : proc_obj.settings('reload'), 'output' : 'plain' } line = pyficache.getline(filename, lineno, opts) if not line: line = linecache.getline(filename, lineno, proc_obj.curframe.f_globals) pass if line and len(line.strip()) != 0: location['text'] = line pass if '<string>' != filename: break pass return location
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/location.py#L9-L65
[ "def", "format_location", "(", "proc_obj", ")", ":", "i_stack", "=", "proc_obj", ".", "curindex", "if", "i_stack", "is", "None", "or", "proc_obj", ".", "stack", "is", "None", ":", "return", "False", "location", "=", "{", "}", "core_obj", "=", "proc_obj", ".", "core", "dbgr_obj", "=", "proc_obj", ".", "debugger", "# Evaluation routines like \"exec\" don't show useful location", "# info. In these cases, we will use the position before that in", "# the stack. Hence the looping below which in practices loops", "# once and sometimes twice.", "while", "i_stack", ">=", "0", ":", "frame_lineno", "=", "proc_obj", ".", "stack", "[", "i_stack", "]", "i_stack", "-=", "1", "frame", ",", "lineno", "=", "frame_lineno", "filename", "=", "Mstack", ".", "frame2file", "(", "core_obj", ",", "frame", ")", "location", "[", "'filename'", "]", "=", "filename", "location", "[", "'fn_name'", "]", "=", "frame", ".", "f_code", ".", "co_name", "location", "[", "'lineno'", "]", "=", "lineno", "if", "'<string>'", "==", "filename", "and", "dbgr_obj", ".", "eval_string", ":", "filename", "=", "pyficache", ".", "unmap_file", "(", "filename", ")", "if", "'<string>'", "==", "filename", ":", "fd", "=", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.py'", ",", "prefix", "=", "'eval_string'", ",", "delete", "=", "False", ")", "fd", ".", "write", "(", "bytes", "(", "dbgr_obj", ".", "eval_string", ",", "'UTF-8'", ")", ")", "fd", ".", "close", "(", ")", "pyficache", ".", "remap_file", "(", "fd", ".", "name", ",", "'<string>'", ")", "filename", "=", "fd", ".", "name", "pass", "pass", "opts", "=", "{", "'reload_on_change'", ":", "proc_obj", ".", "settings", "(", "'reload'", ")", ",", "'output'", ":", "'plain'", "}", "line", "=", "pyficache", ".", "getline", "(", "filename", ",", "lineno", ",", "opts", ")", "if", "not", "line", ":", "line", "=", "linecache", ".", "getline", "(", "filename", ",", "lineno", ",", "proc_obj", ".", "curframe", ".", "f_globals", ")", "pass", "if", "line", "and", "len", "(", "line", ".", "strip", "(", ")", ")", "!=", "0", ":", "location", "[", "'text'", "]", "=", "line", "pass", "if", "'<string>'", "!=", "filename", ":", "break", "pass", "return", "location" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanInterface.msg
used to write to a debugger that is connected to this server; `str' written will have a newline added to it
trepan/interface.py
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.writelines(msg + "\n") pass return
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.writelines(msg + "\n") pass return
[ "used", "to", "write", "to", "a", "debugger", "that", "is", "connected", "to", "this", "server", ";", "str", "written", "will", "have", "a", "newline", "added", "to", "it" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/interface.py#L57-L66
[ "def", "msg", "(", "self", ",", "msg", ")", ":", "if", "hasattr", "(", "self", ".", "output", ",", "'writeline'", ")", ":", "self", ".", "output", ".", "writeline", "(", "msg", ")", "elif", "hasattr", "(", "self", ".", "output", ",", "'writelines'", ")", ":", "self", ".", "output", ".", "writelines", "(", "msg", "+", "\"\\n\"", ")", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
InfoProgram.run
Execution status of the program.
trepan/processor/command/info_subcmd/program.py
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' pass if self.proc.event: msg = 'via a %s event.' % self.proc.event else: msg = '.' self.msg(Mmisc.wrapped_lines(part1, msg, self.settings['width'])) if self.proc.curframe: self.msg("PC offset is %d." % self.proc.curframe.f_lasti) if self.proc.event == 'return': val = self.proc.event_arg part1 = 'Return value is' self.msg(Mmisc.wrapped_lines(part1, self.proc._saferepr(val), self.settings['width'])) pass elif self.proc.event == 'exception': exc_type, exc_value, exc_tb = self.proc.event_arg self.msg('Exception type: %s' % self.proc._saferepr(exc_type)) if exc_value: self.msg('Exception value: %s' % self.proc._saferepr(exc_value)) pass pass self.msg('It stopped %s.' % self.core.stop_reason) if self.proc.event in ['signal', 'exception', 'c_exception']: self.msg('Note: we are stopped *after* running the ' 'line shown.') pass else: if mainfile: part1 = "Python program '%s'" % mainfile msg = "is not currently running. " self.msg(Mmisc.wrapped_lines(part1, msg, self.settings['width'])) else: self.msg('No Python program is currently running.') pass self.msg(self.core.execution_status) pass return False
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' pass if self.proc.event: msg = 'via a %s event.' % self.proc.event else: msg = '.' self.msg(Mmisc.wrapped_lines(part1, msg, self.settings['width'])) if self.proc.curframe: self.msg("PC offset is %d." % self.proc.curframe.f_lasti) if self.proc.event == 'return': val = self.proc.event_arg part1 = 'Return value is' self.msg(Mmisc.wrapped_lines(part1, self.proc._saferepr(val), self.settings['width'])) pass elif self.proc.event == 'exception': exc_type, exc_value, exc_tb = self.proc.event_arg self.msg('Exception type: %s' % self.proc._saferepr(exc_type)) if exc_value: self.msg('Exception value: %s' % self.proc._saferepr(exc_value)) pass pass self.msg('It stopped %s.' % self.core.stop_reason) if self.proc.event in ['signal', 'exception', 'c_exception']: self.msg('Note: we are stopped *after* running the ' 'line shown.') pass else: if mainfile: part1 = "Python program '%s'" % mainfile msg = "is not currently running. " self.msg(Mmisc.wrapped_lines(part1, msg, self.settings['width'])) else: self.msg('No Python program is currently running.') pass self.msg(self.core.execution_status) pass return False
[ "Execution", "status", "of", "the", "program", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/info_subcmd/program.py#L42-L91
[ "def", "run", "(", "self", ",", "args", ")", ":", "mainfile", "=", "self", ".", "core", ".", "filename", "(", "None", ")", "if", "self", ".", "core", ".", "is_running", "(", ")", ":", "if", "mainfile", ":", "part1", "=", "\"Python program '%s' is stopped\"", "%", "mainfile", "else", ":", "part1", "=", "'Program is stopped'", "pass", "if", "self", ".", "proc", ".", "event", ":", "msg", "=", "'via a %s event.'", "%", "self", ".", "proc", ".", "event", "else", ":", "msg", "=", "'.'", "self", ".", "msg", "(", "Mmisc", ".", "wrapped_lines", "(", "part1", ",", "msg", ",", "self", ".", "settings", "[", "'width'", "]", ")", ")", "if", "self", ".", "proc", ".", "curframe", ":", "self", ".", "msg", "(", "\"PC offset is %d.\"", "%", "self", ".", "proc", ".", "curframe", ".", "f_lasti", ")", "if", "self", ".", "proc", ".", "event", "==", "'return'", ":", "val", "=", "self", ".", "proc", ".", "event_arg", "part1", "=", "'Return value is'", "self", ".", "msg", "(", "Mmisc", ".", "wrapped_lines", "(", "part1", ",", "self", ".", "proc", ".", "_saferepr", "(", "val", ")", ",", "self", ".", "settings", "[", "'width'", "]", ")", ")", "pass", "elif", "self", ".", "proc", ".", "event", "==", "'exception'", ":", "exc_type", ",", "exc_value", ",", "exc_tb", "=", "self", ".", "proc", ".", "event_arg", "self", ".", "msg", "(", "'Exception type: %s'", "%", "self", ".", "proc", ".", "_saferepr", "(", "exc_type", ")", ")", "if", "exc_value", ":", "self", ".", "msg", "(", "'Exception value: %s'", "%", "self", ".", "proc", ".", "_saferepr", "(", "exc_value", ")", ")", "pass", "pass", "self", ".", "msg", "(", "'It stopped %s.'", "%", "self", ".", "core", ".", "stop_reason", ")", "if", "self", ".", "proc", ".", "event", "in", "[", "'signal'", ",", "'exception'", ",", "'c_exception'", "]", ":", "self", ".", "msg", "(", "'Note: we are stopped *after* running the '", "'line shown.'", ")", "pass", "else", ":", "if", "mainfile", ":", "part1", "=", "\"Python program '%s'\"", "%", "mainfile", "msg", "=", "\"is not currently running. \"", "self", ".", "msg", "(", "Mmisc", ".", "wrapped_lines", "(", "part1", ",", "msg", ",", "self", ".", "settings", "[", "'width'", "]", ")", ")", "else", ":", "self", ".", "msg", "(", "'No Python program is currently running.'", ")", "pass", "self", ".", "msg", "(", "self", ".", "core", ".", "execution_status", ")", "pass", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerCommand.columnize_commands
List commands arranged in an aligned columns
trepan/processor/command/base_cmd.py
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=' ')
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=' ')
[ "List", "commands", "arranged", "in", "an", "aligned", "columns" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_cmd.py#L58-L63
[ "def", "columnize_commands", "(", "self", ",", "commands", ")", ":", "commands", ".", "sort", "(", ")", "width", "=", "self", ".", "debugger", ".", "settings", "[", "'width'", "]", "return", "columnize", ".", "columnize", "(", "commands", ",", "displaywidth", "=", "width", ",", "lineprefix", "=", "' '", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerCommand.confirm
Convenience short-hand for self.debugger.intf[-1].confirm
trepan/processor/command/base_cmd.py
def confirm(self, msg, default=False): """ Convenience short-hand for self.debugger.intf[-1].confirm """ return self.debugger.intf[-1].confirm(msg, default)
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", "]", ".", "confirm" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_cmd.py#L65-L67
[ "def", "confirm", "(", "self", ",", "msg", ",", "default", "=", "False", ")", ":", "return", "self", ".", "debugger", ".", "intf", "[", "-", "1", "]", ".", "confirm", "(", "msg", ",", "default", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerCommand.errmsg
Convenience short-hand for self.debugger.intf[-1].errmsg
trepan/processor/command/base_cmd.py
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
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", "]", ".", "errmsg" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_cmd.py#L75-L82
[ "def", "errmsg", "(", "self", ",", "msg", ",", "opts", "=", "{", "}", ")", ":", "try", ":", "return", "(", "self", ".", "debugger", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "msg", ")", ")", "except", "EOFError", ":", "# FIXME: what do we do here?", "pass", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerCommand.msg
Convenience short-hand for self.debugger.intf[-1].msg
trepan/processor/command/base_cmd.py
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
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" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_cmd.py#L84-L91
[ "def", "msg", "(", "self", ",", "msg", ",", "opts", "=", "{", "}", ")", ":", "try", ":", "return", "(", "self", ".", "debugger", ".", "intf", "[", "-", "1", "]", ".", "msg", "(", "msg", ")", ")", "except", "EOFError", ":", "# FIXME: what do we do here?", "pass", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerCommand.msg_nocr
Convenience short-hand for self.debugger.intf[-1].msg_nocr
trepan/processor/command/base_cmd.py
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
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
[ "Convenience", "short", "-", "hand", "for", "self", ".", "debugger", ".", "intf", "[", "-", "1", "]", ".", "msg_nocr" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_cmd.py#L93-L100
[ "def", "msg_nocr", "(", "self", ",", "msg", ",", "opts", "=", "{", "}", ")", ":", "try", ":", "return", "(", "self", ".", "debugger", ".", "intf", "[", "-", "1", "]", ".", "msg_nocr", "(", "msg", ")", ")", "except", "EOFError", ":", "# FIXME: what do we do here?", "pass", "return", "None" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
DebuggerCommand.rst_msg
Convert ReStructuredText and run through msg()
trepan/processor/command/base_cmd.py
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)
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)
[ "Convert", "ReStructuredText", "and", "run", "through", "msg", "()" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/base_cmd.py#L102-L107
[ "def", "rst_msg", "(", "self", ",", "text", ",", "opts", "=", "{", "}", ")", ":", "text", "=", "Mformat", ".", "rst_text", "(", "text", ",", "'plain'", "==", "self", ".", "debugger", ".", "settings", "[", "'highlight'", "]", ",", "self", ".", "debugger", ".", "settings", "[", "'width'", "]", ")", "return", "self", ".", "msg", "(", "text", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
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 exception. So assume that sys.exc_info()[2] is where we want to look.
trepan/post_mortem.py
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 exception. So assume that sys.exc_info()[2] is where we want to look.""" try: if inspect.istraceback(sys.last_traceback): # We do have a traceback so prefer that. return sys.last_type, sys.last_value, sys.last_traceback except AttributeError: pass return sys.exc_info()
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 exception. So assume that sys.exc_info()[2] is where we want to look.""" try: if inspect.istraceback(sys.last_traceback): # We do have a traceback so prefer that. return sys.last_type, sys.last_value, sys.last_traceback except AttributeError: pass return sys.exc_info()
[ "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", "we", "want", "to", "look", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/post_mortem.py#L25-L39
[ "def", "get_last_or_frame_exception", "(", ")", ":", "try", ":", "if", "inspect", ".", "istraceback", "(", "sys", ".", "last_traceback", ")", ":", "# We do have a traceback so prefer that.", "return", "sys", ".", "last_type", ",", "sys", ".", "last_value", ",", "sys", ".", "last_traceback", "except", "AttributeError", ":", "pass", "return", "sys", ".", "exc_info", "(", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
post_mortem
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 either we'll assume that sys.exc_info() contains what we want and frameno is the index location of where we want to start. 'frameno' specifies how many frames to ignore in the traceback. The default is 1, that is, we don't need to show the immediate call into post_mortem. If you have wrapper functions that call this one, you may want to increase frameno.
trepan/post_mortem.py
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 either we'll assume that sys.exc_info() contains what we want and frameno is the index location of where we want to start. 'frameno' specifies how many frames to ignore in the traceback. The default is 1, that is, we don't need to show the immediate call into post_mortem. If you have wrapper functions that call this one, you may want to increase frameno. """ if dbg is None: # Check for a global debugger object if Mdebugger.debugger_obj is None: Mdebugger.debugger_obj = Mdebugger.Trepan() pass dbg = Mdebugger.debugger_obj pass re_bogus_file = re.compile("^<.+>$") if exc[0] is None: # frameno+1 because we are about to add one more level of call # in get_last_or_frame_exception exc = get_last_or_frame_exception() if exc[0] is None: print("Can't find traceback for post_mortem " "in sys.last_traceback or sys.exec_info()") return pass exc_type, exc_value, exc_tb = exc dbg.core.execution_status = ('Terminated with unhandled exception %s' % exc_type) # tb has least-recent traceback entry first. We want the most-recent # entry. Also we'll pick out a mainpyfile name if it hasn't previously # been set. if exc_tb is not None: while exc_tb.tb_next is not None: filename = exc_tb.tb_frame.f_code.co_filename if (dbg.mainpyfile and 0 == len(dbg.mainpyfile) and not re_bogus_file.match(filename)): dbg.mainpyfile = filename pass exc_tb = exc_tb.tb_next pass dbg.core.processor.curframe = exc_tb.tb_frame pass if 0 == len(dbg.program_sys_argv): # Fake program (run command) args since we weren't called with any dbg.program_sys_argv = list(sys.argv[1:]) dbg.program_sys_argv[:0] = [dbg.mainpyfile] # if 0 == len(dbg._sys_argv): # # Fake script invocation (restart) args since we don't have any # dbg._sys_argv = list(dbg.program_sys_argv) # dbg._sys_argv[:0] = [__title__] try: # # FIXME: This can be called from except hook in which case we # # need this. Dunno why though. # try: # _pydb_trace.set_trace(t.tb_frame) # except: # pass # Possibly a bug in Python 2.5. Why f.f_lineno is # not always equal to t.tb_lineno, I don't know. f = exc_tb.tb_frame if f and f.f_lineno != exc_tb.tb_lineno : f = f.f_back dbg.core.processor.event_processor(f, 'exception', exc, 'Trepan3k:pm') except DebuggerRestart: while True: sys.argv = list(dbg._program_sys_argv) dbg.msg("Restarting %s with arguments:\n\t%s" % (dbg.filename(dbg.mainpyfile), " ".join(dbg._program_sys_argv[1:]))) try: dbg.run_script(dbg.mainpyfile) except DebuggerRestart: pass pass except DebuggerQuit: pass return
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 either we'll assume that sys.exc_info() contains what we want and frameno is the index location of where we want to start. 'frameno' specifies how many frames to ignore in the traceback. The default is 1, that is, we don't need to show the immediate call into post_mortem. If you have wrapper functions that call this one, you may want to increase frameno. """ if dbg is None: # Check for a global debugger object if Mdebugger.debugger_obj is None: Mdebugger.debugger_obj = Mdebugger.Trepan() pass dbg = Mdebugger.debugger_obj pass re_bogus_file = re.compile("^<.+>$") if exc[0] is None: # frameno+1 because we are about to add one more level of call # in get_last_or_frame_exception exc = get_last_or_frame_exception() if exc[0] is None: print("Can't find traceback for post_mortem " "in sys.last_traceback or sys.exec_info()") return pass exc_type, exc_value, exc_tb = exc dbg.core.execution_status = ('Terminated with unhandled exception %s' % exc_type) # tb has least-recent traceback entry first. We want the most-recent # entry. Also we'll pick out a mainpyfile name if it hasn't previously # been set. if exc_tb is not None: while exc_tb.tb_next is not None: filename = exc_tb.tb_frame.f_code.co_filename if (dbg.mainpyfile and 0 == len(dbg.mainpyfile) and not re_bogus_file.match(filename)): dbg.mainpyfile = filename pass exc_tb = exc_tb.tb_next pass dbg.core.processor.curframe = exc_tb.tb_frame pass if 0 == len(dbg.program_sys_argv): # Fake program (run command) args since we weren't called with any dbg.program_sys_argv = list(sys.argv[1:]) dbg.program_sys_argv[:0] = [dbg.mainpyfile] # if 0 == len(dbg._sys_argv): # # Fake script invocation (restart) args since we don't have any # dbg._sys_argv = list(dbg.program_sys_argv) # dbg._sys_argv[:0] = [__title__] try: # # FIXME: This can be called from except hook in which case we # # need this. Dunno why though. # try: # _pydb_trace.set_trace(t.tb_frame) # except: # pass # Possibly a bug in Python 2.5. Why f.f_lineno is # not always equal to t.tb_lineno, I don't know. f = exc_tb.tb_frame if f and f.f_lineno != exc_tb.tb_lineno : f = f.f_back dbg.core.processor.event_processor(f, 'exception', exc, 'Trepan3k:pm') except DebuggerRestart: while True: sys.argv = list(dbg._program_sys_argv) dbg.msg("Restarting %s with arguments:\n\t%s" % (dbg.filename(dbg.mainpyfile), " ".join(dbg._program_sys_argv[1:]))) try: dbg.run_script(dbg.mainpyfile) except DebuggerRestart: pass pass except DebuggerQuit: pass return
[ "Enter", "debugger", "read", "loop", "after", "your", "program", "has", "crashed", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/post_mortem.py#L80-L168
[ "def", "post_mortem", "(", "exc", "=", "None", ",", "frameno", "=", "1", ",", "dbg", "=", "None", ")", ":", "if", "dbg", "is", "None", ":", "# Check for a global debugger object", "if", "Mdebugger", ".", "debugger_obj", "is", "None", ":", "Mdebugger", ".", "debugger_obj", "=", "Mdebugger", ".", "Trepan", "(", ")", "pass", "dbg", "=", "Mdebugger", ".", "debugger_obj", "pass", "re_bogus_file", "=", "re", ".", "compile", "(", "\"^<.+>$\"", ")", "if", "exc", "[", "0", "]", "is", "None", ":", "# frameno+1 because we are about to add one more level of call", "# in get_last_or_frame_exception", "exc", "=", "get_last_or_frame_exception", "(", ")", "if", "exc", "[", "0", "]", "is", "None", ":", "print", "(", "\"Can't find traceback for post_mortem \"", "\"in sys.last_traceback or sys.exec_info()\"", ")", "return", "pass", "exc_type", ",", "exc_value", ",", "exc_tb", "=", "exc", "dbg", ".", "core", ".", "execution_status", "=", "(", "'Terminated with unhandled exception %s'", "%", "exc_type", ")", "# tb has least-recent traceback entry first. We want the most-recent", "# entry. Also we'll pick out a mainpyfile name if it hasn't previously", "# been set.", "if", "exc_tb", "is", "not", "None", ":", "while", "exc_tb", ".", "tb_next", "is", "not", "None", ":", "filename", "=", "exc_tb", ".", "tb_frame", ".", "f_code", ".", "co_filename", "if", "(", "dbg", ".", "mainpyfile", "and", "0", "==", "len", "(", "dbg", ".", "mainpyfile", ")", "and", "not", "re_bogus_file", ".", "match", "(", "filename", ")", ")", ":", "dbg", ".", "mainpyfile", "=", "filename", "pass", "exc_tb", "=", "exc_tb", ".", "tb_next", "pass", "dbg", ".", "core", ".", "processor", ".", "curframe", "=", "exc_tb", ".", "tb_frame", "pass", "if", "0", "==", "len", "(", "dbg", ".", "program_sys_argv", ")", ":", "# Fake program (run command) args since we weren't called with any", "dbg", ".", "program_sys_argv", "=", "list", "(", "sys", ".", "argv", "[", "1", ":", "]", ")", "dbg", ".", "program_sys_argv", "[", ":", "0", "]", "=", "[", "dbg", ".", "mainpyfile", "]", "# if 0 == len(dbg._sys_argv):", "# # Fake script invocation (restart) args since we don't have any", "# dbg._sys_argv = list(dbg.program_sys_argv)", "# dbg._sys_argv[:0] = [__title__]", "try", ":", "# # FIXME: This can be called from except hook in which case we", "# # need this. Dunno why though.", "# try:", "# _pydb_trace.set_trace(t.tb_frame)", "# except:", "# pass", "# Possibly a bug in Python 2.5. Why f.f_lineno is", "# not always equal to t.tb_lineno, I don't know.", "f", "=", "exc_tb", ".", "tb_frame", "if", "f", "and", "f", ".", "f_lineno", "!=", "exc_tb", ".", "tb_lineno", ":", "f", "=", "f", ".", "f_back", "dbg", ".", "core", ".", "processor", ".", "event_processor", "(", "f", ",", "'exception'", ",", "exc", ",", "'Trepan3k:pm'", ")", "except", "DebuggerRestart", ":", "while", "True", ":", "sys", ".", "argv", "=", "list", "(", "dbg", ".", "_program_sys_argv", ")", "dbg", ".", "msg", "(", "\"Restarting %s with arguments:\\n\\t%s\"", "%", "(", "dbg", ".", "filename", "(", "dbg", ".", "mainpyfile", ")", ",", "\" \"", ".", "join", "(", "dbg", ".", "_program_sys_argv", "[", "1", ":", "]", ")", ")", ")", "try", ":", "dbg", ".", "run_script", "(", "dbg", ".", "mainpyfile", ")", "except", "DebuggerRestart", ":", "pass", "pass", "except", "DebuggerQuit", ":", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TCPServer.close
Closes both socket and server connection.
trepan/inout/tcpserver.py
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' return
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' return
[ "Closes", "both", "socket", "and", "server", "connection", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/tcpserver.py#L56-L66
[ "def", "close", "(", "self", ")", ":", "self", ".", "state", "=", "'closing'", "if", "self", ".", "inout", ":", "self", ".", "inout", ".", "close", "(", ")", "pass", "self", ".", "state", "=", "'closing connection'", "if", "self", ".", "conn", ":", "self", ".", "conn", ".", "close", "(", ")", "self", ".", "state", "=", "'disconnected'", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TCPServer.write
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.
trepan/inout/tcpserver.py
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 = Mtcpfns.pack_msg(msg) while len(buffer) > Mtcpfns.TCP_MAX_PACKET: self.conn.send(buffer[:Mtcpfns.TCP_MAX_PACKET]) buffer = buffer[Mtcpfns.TCP_MAX_PACKET:] return self.conn.send(buffer)
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 = Mtcpfns.pack_msg(msg) while len(buffer) > Mtcpfns.TCP_MAX_PACKET: self.conn.send(buffer[:Mtcpfns.TCP_MAX_PACKET]) buffer = buffer[Mtcpfns.TCP_MAX_PACKET:] return self.conn.send(buffer)
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/tcpserver.py#L150-L162
[ "def", "write", "(", "self", ",", "msg", ")", ":", "if", "self", ".", "state", "!=", "'connected'", ":", "self", ".", "wait_for_connect", "(", ")", "pass", "buffer", "=", "Mtcpfns", ".", "pack_msg", "(", "msg", ")", "while", "len", "(", "buffer", ")", ">", "Mtcpfns", ".", "TCP_MAX_PACKET", ":", "self", ".", "conn", ".", "send", "(", "buffer", "[", ":", "Mtcpfns", ".", "TCP_MAX_PACKET", "]", ")", "buffer", "=", "buffer", "[", "Mtcpfns", ".", "TCP_MAX_PACKET", ":", "]", "return", "self", ".", "conn", ".", "send", "(", "buffer", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
complete_token_filtered
Find all starting matches in dictionary *aliases* that start with *prefix*, but filter out any matches already in *expanded*.
trepan/processor/complete.py
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(prefix)] and not ( cmd in aliases and expanded not in aliases[cmd]) return sorted(results, key=lambda pair: pair[0])
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(prefix)] and not ( cmd in aliases and expanded not in aliases[cmd]) return sorted(results, key=lambda pair: pair[0])
[ "Find", "all", "starting", "matches", "in", "dictionary", "*", "aliases", "*", "that", "start", "with", "*", "prefix", "*", "but", "filter", "out", "any", "matches", "already", "in", "*", "expanded", "*", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/complete.py#L22-L32
[ "def", "complete_token_filtered", "(", "aliases", ",", "prefix", ",", "expanded", ")", ":", "complete_ary", "=", "list", "(", "aliases", ".", "keys", "(", ")", ")", "results", "=", "[", "cmd", "for", "cmd", "in", "complete_ary", "if", "cmd", ".", "startswith", "(", "prefix", ")", "]", "and", "not", "(", "cmd", "in", "aliases", "and", "expanded", "not", "in", "aliases", "[", "cmd", "]", ")", "return", "sorted", "(", "results", ",", "key", "=", "lambda", "pair", ":", "pair", "[", "0", "]", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
complete_identifier
Complete an arbitrary expression.
trepan/processor/complete.py
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.curframe.f_globals.copy() ns.update(cmd.proc.curframe.f_locals) if '.' in prefix: # Walk an attribute chain up to the last part, similar to what # rlcompleter does. This will bail if any of the parts are not # simple attribute access, which is what we want. dotted = prefix.split('.') try: obj = ns[dotted[0]] for part in dotted[1:-1]: obj = getattr(obj, part) except (KeyError, AttributeError): return [] pre_prefix = '.'.join(dotted[:-1]) + '.' return [pre_prefix + n for n in dir(obj) if n.startswith(dotted[-1])] else: # Complete a simple name. return Mcomplete.complete_token(ns.keys(), prefix)
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.curframe.f_globals.copy() ns.update(cmd.proc.curframe.f_locals) if '.' in prefix: # Walk an attribute chain up to the last part, similar to what # rlcompleter does. This will bail if any of the parts are not # simple attribute access, which is what we want. dotted = prefix.split('.') try: obj = ns[dotted[0]] for part in dotted[1:-1]: obj = getattr(obj, part) except (KeyError, AttributeError): return [] pre_prefix = '.'.join(dotted[:-1]) + '.' return [pre_prefix + n for n in dir(obj) if n.startswith(dotted[-1])] else: # Complete a simple name. return Mcomplete.complete_token(ns.keys(), prefix)
[ "Complete", "an", "arbitrary", "expression", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/complete.py#L125-L149
[ "def", "complete_identifier", "(", "cmd", ",", "prefix", ")", ":", "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", ".", "curframe", ".", "f_globals", ".", "copy", "(", ")", "ns", ".", "update", "(", "cmd", ".", "proc", ".", "curframe", ".", "f_locals", ")", "if", "'.'", "in", "prefix", ":", "# Walk an attribute chain up to the last part, similar to what", "# rlcompleter does. This will bail if any of the parts are not", "# simple attribute access, which is what we want.", "dotted", "=", "prefix", ".", "split", "(", "'.'", ")", "try", ":", "obj", "=", "ns", "[", "dotted", "[", "0", "]", "]", "for", "part", "in", "dotted", "[", "1", ":", "-", "1", "]", ":", "obj", "=", "getattr", "(", "obj", ",", "part", ")", "except", "(", "KeyError", ",", "AttributeError", ")", ":", "return", "[", "]", "pre_prefix", "=", "'.'", ".", "join", "(", "dotted", "[", ":", "-", "1", "]", ")", "+", "'.'", "return", "[", "pre_prefix", "+", "n", "for", "n", "in", "dir", "(", "obj", ")", "if", "n", ".", "startswith", "(", "dotted", "[", "-", "1", "]", ")", "]", "else", ":", "# Complete a simple name.", "return", "Mcomplete", ".", "complete_token", "(", "ns", ".", "keys", "(", ")", ",", "prefix", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
Processor.errmsg
Convenience short-hand for self.intf[-1].errmsg
trepan/vprocessor.py
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))
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))
[ "Convenience", "short", "-", "hand", "for", "self", ".", "intf", "[", "-", "1", "]", ".", "errmsg" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/vprocessor.py#L39-L44
[ "def", "errmsg", "(", "self", ",", "message", ",", "opts", "=", "{", "}", ")", ":", "if", "'plain'", "!=", "self", ".", "debugger", ".", "settings", "[", "'highlight'", "]", ":", "message", "=", "colorize", "(", "'standout'", ",", "message", ")", "pass", "return", "(", "self", ".", "intf", "[", "-", "1", "]", ".", "errmsg", "(", "message", ")", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
Processor.rst_msg
Convert ReStructuredText and run through msg()
trepan/vprocessor.py
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.msg(text)
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.msg(text)
[ "Convert", "ReStructuredText", "and", "run", "through", "msg", "()" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/vprocessor.py#L57-L63
[ "def", "rst_msg", "(", "self", ",", "text", ",", "opts", "=", "{", "}", ")", ":", "from", "trepan", ".", "lib", ".", "format", "import", "rst_text", "text", "=", "rst_text", "(", "text", ",", "'plain'", "==", "self", ".", "debugger", ".", "settings", "[", "'highlight'", "]", ",", "self", ".", "debugger", ".", "settings", "[", "'width'", "]", ")", "return", "self", ".", "msg", "(", "text", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
PythonCommand.dbgr
Invoke a debugger command from inside a python shell called inside the debugger.
trepan/processor/command/bpy.py
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
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
[ "Invoke", "a", "debugger", "command", "from", "inside", "a", "python", "shell", "called", "inside", "the", "debugger", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/bpy.py#L44-L51
[ "def", "dbgr", "(", "self", ",", "string", ")", ":", "print", "(", "''", ")", "self", ".", "proc", ".", "cmd_queue", ".", "append", "(", "string", ")", "self", ".", "proc", ".", "process_command", "(", ")", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
QuitCommand.nothread_quit
quit command when there's just one thread.
trepan/bwprocessor/command/quit.py
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.proc.response) raise Mexcept.DebuggerQuit
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.proc.response) raise Mexcept.DebuggerQuit
[ "quit", "command", "when", "there", "s", "just", "one", "thread", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/bwprocessor/command/quit.py#L43-L51
[ "def", "nothread_quit", "(", "self", ",", "arg", ")", ":", "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", ".", "proc", ".", "response", ")", "raise", "Mexcept", ".", "DebuggerQuit" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
parse_addr_list_cmd
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.
trepan/processor/cmd_addrlist.py
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(('', '.', '+', '-')): if text == '.': location = resolve_address_location(proc, '.') return (location.path, location.line_number, True, location.line_number + listsize, True, location.method) if proc.list_offset is None: proc.errmsg("Don't have previous list location") return INVALID_PARSE_LIST filename = proc.list_filename if text == '+': first = max(0, proc.list_offset-1) elif text == '-': # FIXME: not quite right for offsets if proc.list_lineno == 1 + listsize: proc.errmsg("Already at start of %s." % proc.list_filename) return INVALID_PARSE_LIST first = max(1, proc.list_lineno - (2*listsize) - 1) elif text == '': # Continue from where we last left off first = proc.list_offset + 1 last = first + listsize - 1 return filename, first, True, last, True, proc.list_object last = first + listsize - 1 return filename, first, True, last, True, proc.list_object else: try: list_range = build_arange(text) except LocationError as e: proc.errmsg("Error in parsing list range at or around:") proc.errmsg(e.text) proc.errmsg(e.text_cursor) return INVALID_PARSE_LIST except ScannerError as e: proc.errmsg("Lexical error in parsing list range at or around:") proc.errmsg(e.text) proc.errmsg(e.text_cursor) return INVALID_PARSE_LIST if list_range.first is None: # Last must have been given assert isinstance(list_range.last, Location) location = resolve_address_location(proc, list_range.last) if not location: return INVALID_PARSE_LIST last = location.line_number if location.is_address: raise RuntimeError("We don't handle ending offsets") else: first = max(1, last - listsize) return location.path, first, False, last, False, location.method elif isinstance(list_range.first, int): first = list_range.first location = resolve_address_location(proc, list_range.last) if not location: return INVALID_PARSE_LIST filename = location.path last = location.line_number if not location.is_address and last < first: # Treat as a count rather than an absolute location last = first + last return location.path, first, False, last, location.is_address, location.method else: # First is location. Last may be empty or a number/address assert isinstance(list_range.first, Location) location = resolve_address_location(proc, list_range.first) if not location: return INVALID_PARSE_LIST first = location.line_number first_is_addr = location.is_address last_is_addr = False last = list_range.last if isinstance(last, str): # Is an offset +number assert last[0] in ('+', '*') last_is_addr = last[0] == '*' if last_is_addr: last = int(last[1:]) else: last = first + int(last[1:]) elif not last: last_is_addr = True last = first + listsize elif last < first: # Treat as a count rather than an absolute location last = first + last return location.path, first, first_is_addr, last, last_is_addr, location.method pass return
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(('', '.', '+', '-')): if text == '.': location = resolve_address_location(proc, '.') return (location.path, location.line_number, True, location.line_number + listsize, True, location.method) if proc.list_offset is None: proc.errmsg("Don't have previous list location") return INVALID_PARSE_LIST filename = proc.list_filename if text == '+': first = max(0, proc.list_offset-1) elif text == '-': # FIXME: not quite right for offsets if proc.list_lineno == 1 + listsize: proc.errmsg("Already at start of %s." % proc.list_filename) return INVALID_PARSE_LIST first = max(1, proc.list_lineno - (2*listsize) - 1) elif text == '': # Continue from where we last left off first = proc.list_offset + 1 last = first + listsize - 1 return filename, first, True, last, True, proc.list_object last = first + listsize - 1 return filename, first, True, last, True, proc.list_object else: try: list_range = build_arange(text) except LocationError as e: proc.errmsg("Error in parsing list range at or around:") proc.errmsg(e.text) proc.errmsg(e.text_cursor) return INVALID_PARSE_LIST except ScannerError as e: proc.errmsg("Lexical error in parsing list range at or around:") proc.errmsg(e.text) proc.errmsg(e.text_cursor) return INVALID_PARSE_LIST if list_range.first is None: # Last must have been given assert isinstance(list_range.last, Location) location = resolve_address_location(proc, list_range.last) if not location: return INVALID_PARSE_LIST last = location.line_number if location.is_address: raise RuntimeError("We don't handle ending offsets") else: first = max(1, last - listsize) return location.path, first, False, last, False, location.method elif isinstance(list_range.first, int): first = list_range.first location = resolve_address_location(proc, list_range.last) if not location: return INVALID_PARSE_LIST filename = location.path last = location.line_number if not location.is_address and last < first: # Treat as a count rather than an absolute location last = first + last return location.path, first, False, last, location.is_address, location.method else: # First is location. Last may be empty or a number/address assert isinstance(list_range.first, Location) location = resolve_address_location(proc, list_range.first) if not location: return INVALID_PARSE_LIST first = location.line_number first_is_addr = location.is_address last_is_addr = False last = list_range.last if isinstance(last, str): # Is an offset +number assert last[0] in ('+', '*') last_is_addr = last[0] == '*' if last_is_addr: last = int(last[1:]) else: last = first + int(last[1:]) elif not last: last_is_addr = True last = first + listsize elif last < first: # Treat as a count rather than an absolute location last = first + last return location.path, first, first_is_addr, last, last_is_addr, location.method pass 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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/cmd_addrlist.py#L23-L122
[ "def", "parse_addr_list_cmd", "(", "proc", ",", "args", ",", "listsize", "=", "40", ")", ":", "text", "=", "proc", ".", "current_command", "[", "len", "(", "args", "[", "0", "]", ")", "+", "1", ":", "]", ".", "strip", "(", ")", "if", "text", "in", "frozenset", "(", "(", "''", ",", "'.'", ",", "'+'", ",", "'-'", ")", ")", ":", "if", "text", "==", "'.'", ":", "location", "=", "resolve_address_location", "(", "proc", ",", "'.'", ")", "return", "(", "location", ".", "path", ",", "location", ".", "line_number", ",", "True", ",", "location", ".", "line_number", "+", "listsize", ",", "True", ",", "location", ".", "method", ")", "if", "proc", ".", "list_offset", "is", "None", ":", "proc", ".", "errmsg", "(", "\"Don't have previous list location\"", ")", "return", "INVALID_PARSE_LIST", "filename", "=", "proc", ".", "list_filename", "if", "text", "==", "'+'", ":", "first", "=", "max", "(", "0", ",", "proc", ".", "list_offset", "-", "1", ")", "elif", "text", "==", "'-'", ":", "# FIXME: not quite right for offsets", "if", "proc", ".", "list_lineno", "==", "1", "+", "listsize", ":", "proc", ".", "errmsg", "(", "\"Already at start of %s.\"", "%", "proc", ".", "list_filename", ")", "return", "INVALID_PARSE_LIST", "first", "=", "max", "(", "1", ",", "proc", ".", "list_lineno", "-", "(", "2", "*", "listsize", ")", "-", "1", ")", "elif", "text", "==", "''", ":", "# Continue from where we last left off", "first", "=", "proc", ".", "list_offset", "+", "1", "last", "=", "first", "+", "listsize", "-", "1", "return", "filename", ",", "first", ",", "True", ",", "last", ",", "True", ",", "proc", ".", "list_object", "last", "=", "first", "+", "listsize", "-", "1", "return", "filename", ",", "first", ",", "True", ",", "last", ",", "True", ",", "proc", ".", "list_object", "else", ":", "try", ":", "list_range", "=", "build_arange", "(", "text", ")", "except", "LocationError", "as", "e", ":", "proc", ".", "errmsg", "(", "\"Error in parsing list range at or around:\"", ")", "proc", ".", "errmsg", "(", "e", ".", "text", ")", "proc", ".", "errmsg", "(", "e", ".", "text_cursor", ")", "return", "INVALID_PARSE_LIST", "except", "ScannerError", "as", "e", ":", "proc", ".", "errmsg", "(", "\"Lexical error in parsing list range at or around:\"", ")", "proc", ".", "errmsg", "(", "e", ".", "text", ")", "proc", ".", "errmsg", "(", "e", ".", "text_cursor", ")", "return", "INVALID_PARSE_LIST", "if", "list_range", ".", "first", "is", "None", ":", "# Last must have been given", "assert", "isinstance", "(", "list_range", ".", "last", ",", "Location", ")", "location", "=", "resolve_address_location", "(", "proc", ",", "list_range", ".", "last", ")", "if", "not", "location", ":", "return", "INVALID_PARSE_LIST", "last", "=", "location", ".", "line_number", "if", "location", ".", "is_address", ":", "raise", "RuntimeError", "(", "\"We don't handle ending offsets\"", ")", "else", ":", "first", "=", "max", "(", "1", ",", "last", "-", "listsize", ")", "return", "location", ".", "path", ",", "first", ",", "False", ",", "last", ",", "False", ",", "location", ".", "method", "elif", "isinstance", "(", "list_range", ".", "first", ",", "int", ")", ":", "first", "=", "list_range", ".", "first", "location", "=", "resolve_address_location", "(", "proc", ",", "list_range", ".", "last", ")", "if", "not", "location", ":", "return", "INVALID_PARSE_LIST", "filename", "=", "location", ".", "path", "last", "=", "location", ".", "line_number", "if", "not", "location", ".", "is_address", "and", "last", "<", "first", ":", "# Treat as a count rather than an absolute location", "last", "=", "first", "+", "last", "return", "location", ".", "path", ",", "first", ",", "False", ",", "last", ",", "location", ".", "is_address", ",", "location", ".", "method", "else", ":", "# First is location. Last may be empty or a number/address", "assert", "isinstance", "(", "list_range", ".", "first", ",", "Location", ")", "location", "=", "resolve_address_location", "(", "proc", ",", "list_range", ".", "first", ")", "if", "not", "location", ":", "return", "INVALID_PARSE_LIST", "first", "=", "location", ".", "line_number", "first_is_addr", "=", "location", ".", "is_address", "last_is_addr", "=", "False", "last", "=", "list_range", ".", "last", "if", "isinstance", "(", "last", ",", "str", ")", ":", "# Is an offset +number", "assert", "last", "[", "0", "]", "in", "(", "'+'", ",", "'*'", ")", "last_is_addr", "=", "last", "[", "0", "]", "==", "'*'", "if", "last_is_addr", ":", "last", "=", "int", "(", "last", "[", "1", ":", "]", ")", "else", ":", "last", "=", "first", "+", "int", "(", "last", "[", "1", ":", "]", ")", "elif", "not", "last", ":", "last_is_addr", "=", "True", "last", "=", "first", "+", "listsize", "elif", "last", "<", "first", ":", "# Treat as a count rather than an absolute location", "last", "=", "first", "+", "last", "return", "location", ".", "path", ",", "first", ",", "first_is_addr", ",", "last", ",", "last_is_addr", ",", "location", ".", "method", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.add_ignore
Add `frame_or_fn' to the list of functions that are not to be debugged
trepan/lib/core.py
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
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
[ "Add", "frame_or_fn", "to", "the", "list", "of", "functions", "that", "are", "not", "to", "be", "debugged" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L133-L139
[ "def", "add_ignore", "(", "self", ",", "*", "frames_or_fns", ")", ":", "for", "frame_or_fn", "in", "frames_or_fns", ":", "rc", "=", "self", ".", "ignore_filter", ".", "add_include", "(", "frame_or_fn", ")", "pass", "return", "rc" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.canonic
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 change over the course of execution. If filename is enclosed in < ... >, then we assume it is one of the bogus internal Python names like <string> which is seen for example when executing "exec cmd".
trepan/lib/core.py
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 change over the course of execution. If filename is enclosed in < ... >, then we assume it is one of the bogus internal Python names like <string> which is seen for example when executing "exec cmd". """ if filename == "<" + filename[1:-1] + ">": return filename canonic = self.filename_cache.get(filename) if not canonic: lead_dir = filename.split(os.sep)[0] if lead_dir == os.curdir or lead_dir == os.pardir: # We may have invoked the program from a directory # other than where the program resides. filename is # relative to where the program resides. So make sure # to use that. canonic = os.path.abspath(os.path.join(self.main_dirname, filename)) else: canonic = os.path.abspath(filename) pass if not os.path.isfile(canonic): canonic = Mclifns.search_file(filename, self.search_path, self.main_dirname) # FIXME: is this is right for utter failure? if not canonic: canonic = filename pass canonic = os.path.realpath(os.path.normcase(canonic)) self.filename_cache[filename] = canonic return canonic
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 change over the course of execution. If filename is enclosed in < ... >, then we assume it is one of the bogus internal Python names like <string> which is seen for example when executing "exec cmd". """ if filename == "<" + filename[1:-1] + ">": return filename canonic = self.filename_cache.get(filename) if not canonic: lead_dir = filename.split(os.sep)[0] if lead_dir == os.curdir or lead_dir == os.pardir: # We may have invoked the program from a directory # other than where the program resides. filename is # relative to where the program resides. So make sure # to use that. canonic = os.path.abspath(os.path.join(self.main_dirname, filename)) else: canonic = os.path.abspath(filename) pass if not os.path.isfile(canonic): canonic = Mclifns.search_file(filename, self.search_path, self.main_dirname) # FIXME: is this is right for utter failure? if not canonic: canonic = filename pass canonic = os.path.realpath(os.path.normcase(canonic)) self.filename_cache[filename] = canonic return canonic
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L141-L177
[ "def", "canonic", "(", "self", ",", "filename", ")", ":", "if", "filename", "==", "\"<\"", "+", "filename", "[", "1", ":", "-", "1", "]", "+", "\">\"", ":", "return", "filename", "canonic", "=", "self", ".", "filename_cache", ".", "get", "(", "filename", ")", "if", "not", "canonic", ":", "lead_dir", "=", "filename", ".", "split", "(", "os", ".", "sep", ")", "[", "0", "]", "if", "lead_dir", "==", "os", ".", "curdir", "or", "lead_dir", "==", "os", ".", "pardir", ":", "# We may have invoked the program from a directory", "# other than where the program resides. filename is", "# relative to where the program resides. So make sure", "# to use that.", "canonic", "=", "os", ".", "path", ".", "abspath", "(", "os", ".", "path", ".", "join", "(", "self", ".", "main_dirname", ",", "filename", ")", ")", "else", ":", "canonic", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "pass", "if", "not", "os", ".", "path", ".", "isfile", "(", "canonic", ")", ":", "canonic", "=", "Mclifns", ".", "search_file", "(", "filename", ",", "self", ".", "search_path", ",", "self", ".", "main_dirname", ")", "# FIXME: is this is right for utter failure?", "if", "not", "canonic", ":", "canonic", "=", "filename", "pass", "canonic", "=", "os", ".", "path", ".", "realpath", "(", "os", ".", "path", ".", "normcase", "(", "canonic", ")", ")", "self", ".", "filename_cache", "[", "filename", "]", "=", "canonic", "return", "canonic" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.filename
Return filename or the basename of that depending on the basename setting
trepan/lib/core.py
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.debugger.settings['basename']: return(os.path.basename(filename)) return filename
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.debugger.settings['basename']: return(os.path.basename(filename)) return filename
[ "Return", "filename", "or", "the", "basename", "of", "that", "depending", "on", "the", "basename", "setting" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L184-L194
[ "def", "filename", "(", "self", ",", "filename", "=", "None", ")", ":", "if", "filename", "is", "None", ":", "if", "self", ".", "debugger", ".", "mainpyfile", ":", "filename", "=", "self", ".", "debugger", ".", "mainpyfile", "else", ":", "return", "None", "if", "self", ".", "debugger", ".", "settings", "[", "'basename'", "]", ":", "return", "(", "os", ".", "path", ".", "basename", "(", "filename", ")", ")", "return", "filename" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.is_started
Return True if debugging is in progress.
trepan/lib/core.py
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))
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))
[ "Return", "True", "if", "debugging", "is", "in", "progress", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L199-L203
[ "def", "is_started", "(", "self", ")", ":", "return", "(", "tracer", ".", "is_started", "(", ")", "and", "not", "self", ".", "trace_hook_suspend", "and", "tracer", ".", "find_hook", "(", "self", ".", "trace_dispatch", ")", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.start
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 debugger. See START_OPTS of module default.
trepan/lib/core.py
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 debugger. See START_OPTS of module default. """ # The below is our fancy equivalent of: # sys.settrace(self._trace_dispatch) try: self.trace_hook_suspend = True get_option = lambda key: Mmisc.option_set(opts, key, default.START_OPTS) add_hook_opts = get_option('add_hook_opts') # Has tracer been started? if not tracer.is_started() or get_option('force'): # FIXME: should filter out opts not for tracer tracer_start_opts = default.START_OPTS.copy() if opts: tracer_start_opts.update(opts.get('tracer_start', {})) tracer_start_opts['trace_fn'] = self.trace_dispatch tracer_start_opts['add_hook_opts'] = add_hook_opts tracer.start(tracer_start_opts) elif not tracer.find_hook(self.trace_dispatch): tracer.add_hook(self.trace_dispatch, add_hook_opts) pass self.execution_status = 'Running' finally: self.trace_hook_suspend = False return
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 debugger. See START_OPTS of module default. """ # The below is our fancy equivalent of: # sys.settrace(self._trace_dispatch) try: self.trace_hook_suspend = True get_option = lambda key: Mmisc.option_set(opts, key, default.START_OPTS) add_hook_opts = get_option('add_hook_opts') # Has tracer been started? if not tracer.is_started() or get_option('force'): # FIXME: should filter out opts not for tracer tracer_start_opts = default.START_OPTS.copy() if opts: tracer_start_opts.update(opts.get('tracer_start', {})) tracer_start_opts['trace_fn'] = self.trace_dispatch tracer_start_opts['add_hook_opts'] = add_hook_opts tracer.start(tracer_start_opts) elif not tracer.find_hook(self.trace_dispatch): tracer.add_hook(self.trace_dispatch, add_hook_opts) pass self.execution_status = 'Running' finally: self.trace_hook_suspend = False return
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L210-L244
[ "def", "start", "(", "self", ",", "opts", "=", "None", ")", ":", "# The below is our fancy equivalent of:", "# sys.settrace(self._trace_dispatch)", "try", ":", "self", ".", "trace_hook_suspend", "=", "True", "get_option", "=", "lambda", "key", ":", "Mmisc", ".", "option_set", "(", "opts", ",", "key", ",", "default", ".", "START_OPTS", ")", "add_hook_opts", "=", "get_option", "(", "'add_hook_opts'", ")", "# Has tracer been started?", "if", "not", "tracer", ".", "is_started", "(", ")", "or", "get_option", "(", "'force'", ")", ":", "# FIXME: should filter out opts not for tracer", "tracer_start_opts", "=", "default", ".", "START_OPTS", ".", "copy", "(", ")", "if", "opts", ":", "tracer_start_opts", ".", "update", "(", "opts", ".", "get", "(", "'tracer_start'", ",", "{", "}", ")", ")", "tracer_start_opts", "[", "'trace_fn'", "]", "=", "self", ".", "trace_dispatch", "tracer_start_opts", "[", "'add_hook_opts'", "]", "=", "add_hook_opts", "tracer", ".", "start", "(", "tracer_start_opts", ")", "elif", "not", "tracer", ".", "find_hook", "(", "self", ".", "trace_dispatch", ")", ":", "tracer", ".", "add_hook", "(", "self", ".", "trace_dispatch", ",", "add_hook_opts", ")", "pass", "self", ".", "execution_status", "=", "'Running'", "finally", ":", "self", ".", "trace_hook_suspend", "=", "False", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.is_stop_here
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 stepping, next'ing, finish'ing, and, if so, whether there is an ignore counter.
trepan/lib/core.py
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 stepping, next'ing, finish'ing, and, if so, whether there is an ignore counter. """ # Add an generic event filter here? # FIXME TODO: Check for # - thread switching (under set option) # Check for "next" and "finish" stopping via stop_level # Do we want a different line and if so, # do we have one? lineno = frame.f_lineno filename = frame.f_code.co_filename if self.different_line and event == 'line': if self.last_lineno == lineno and self.last_filename == filename: return False pass self.last_lineno = lineno self.last_filename = filename if self.stop_level is not None: if frame != self.last_frame: # Recompute stack_depth self.last_level = Mstack.count_frames(frame) self.last_frame = frame pass if self.last_level > self.stop_level: return False elif self.last_level == self.stop_level and \ self.stop_on_finish and event in ['return', 'c_return']: self.stop_level = None self.stop_reason = "in return for 'finish' command" return True pass # Check for stepping if self._is_step_next_stop(event): self.stop_reason = 'at a stepping statement' return True 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 stepping, next'ing, finish'ing, and, if so, whether there is an ignore counter. """ # Add an generic event filter here? # FIXME TODO: Check for # - thread switching (under set option) # Check for "next" and "finish" stopping via stop_level # Do we want a different line and if so, # do we have one? lineno = frame.f_lineno filename = frame.f_code.co_filename if self.different_line and event == 'line': if self.last_lineno == lineno and self.last_filename == filename: return False pass self.last_lineno = lineno self.last_filename = filename if self.stop_level is not None: if frame != self.last_frame: # Recompute stack_depth self.last_level = Mstack.count_frames(frame) self.last_frame = frame pass if self.last_level > self.stop_level: return False elif self.last_level == self.stop_level and \ self.stop_on_finish and event in ['return', 'c_return']: self.stop_level = None self.stop_reason = "in return for 'finish' command" return True pass # Check for stepping if self._is_step_next_stop(event): self.stop_reason = 'at a stepping statement' return True return False
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L323-L370
[ "def", "is_stop_here", "(", "self", ",", "frame", ",", "event", ",", "arg", ")", ":", "# Add an generic event filter here?", "# FIXME TODO: Check for", "# - thread switching (under set option)", "# Check for \"next\" and \"finish\" stopping via stop_level", "# Do we want a different line and if so,", "# do we have one?", "lineno", "=", "frame", ".", "f_lineno", "filename", "=", "frame", ".", "f_code", ".", "co_filename", "if", "self", ".", "different_line", "and", "event", "==", "'line'", ":", "if", "self", ".", "last_lineno", "==", "lineno", "and", "self", ".", "last_filename", "==", "filename", ":", "return", "False", "pass", "self", ".", "last_lineno", "=", "lineno", "self", ".", "last_filename", "=", "filename", "if", "self", ".", "stop_level", "is", "not", "None", ":", "if", "frame", "!=", "self", ".", "last_frame", ":", "# Recompute stack_depth", "self", ".", "last_level", "=", "Mstack", ".", "count_frames", "(", "frame", ")", "self", ".", "last_frame", "=", "frame", "pass", "if", "self", ".", "last_level", ">", "self", ".", "stop_level", ":", "return", "False", "elif", "self", ".", "last_level", "==", "self", ".", "stop_level", "and", "self", ".", "stop_on_finish", "and", "event", "in", "[", "'return'", ",", "'c_return'", "]", ":", "self", ".", "stop_level", "=", "None", "self", ".", "stop_reason", "=", "\"in return for 'finish' command\"", "return", "True", "pass", "# Check for stepping", "if", "self", ".", "_is_step_next_stop", "(", "event", ")", ":", "self", ".", "stop_reason", "=", "'at a stepping statement'", "return", "True", "return", "False" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.set_next
Sets to stop on the next event that happens in frame 'frame'.
trepan/lib/core.py
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_frame = frame self.stop_on_finish = False self.step_ignore = step_ignore return
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_frame = frame self.stop_on_finish = False self.step_ignore = step_ignore return
[ "Sets", "to", "stop", "on", "the", "next", "event", "that", "happens", "in", "frame", "frame", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L382-L390
[ "def", "set_next", "(", "self", ",", "frame", ",", "step_ignore", "=", "0", ",", "step_events", "=", "None", ")", ":", "self", ".", "step_events", "=", "None", "# Consider all events", "self", ".", "stop_level", "=", "Mstack", ".", "count_frames", "(", "frame", ")", "self", ".", "last_level", "=", "self", ".", "stop_level", "self", ".", "last_frame", "=", "frame", "self", ".", "stop_on_finish", "=", "False", "self", ".", "step_ignore", "=", "step_ignore", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
TrepanCore.trace_dispatch
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.
trepan/lib/core.py
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 seems processor-specific I think it best to distribute the checks.''' # For now we only allow one instance in a process # In Python 2.6 and beyond one can use "with threading.Lock():" try: self.debugger_lock.acquire() if self.trace_hook_suspend: return None self.event = event # FIXME: Understand what's going on here better. # When None gets returned, the frame's f_trace seems to get set # to None. Somehow this is changing other frames when get passed # to this routine which also have their f_trace set to None. # This will disallow a command like "jump" from working properly, # which will give a cryptic the message on setting f_lineno: # f_lineno can only be set by a trace function if self.ignore_filter and self.ignore_filter.is_included(frame): return True if self.debugger.settings['trace']: print_event_set = self.debugger.settings['printset'] if self.event in print_event_set: self.trace_processor.event_processor(frame, self.event, arg) pass pass if self.until_condition: if not self.matches_condition(frame): return True pass trace_event_set = self.debugger.settings['events'] if trace_event_set is None or self.event not in trace_event_set: return True # I think we *have* to run is_stop_here() before # is_break_here() because is_stop_here() sets various # stepping counts. But it might be more desirable from the # user's standpoint to test for breaks before steps. In # this case we will need to factor out the counting # updates. if ( self.is_stop_here(frame, event, arg) or self.is_break_here(frame, arg) ): # Run the event processor return self.processor.event_processor(frame, self.event, arg) return True finally: try: self.debugger_lock.release() except: pass pass pass
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 seems processor-specific I think it best to distribute the checks.''' # For now we only allow one instance in a process # In Python 2.6 and beyond one can use "with threading.Lock():" try: self.debugger_lock.acquire() if self.trace_hook_suspend: return None self.event = event # FIXME: Understand what's going on here better. # When None gets returned, the frame's f_trace seems to get set # to None. Somehow this is changing other frames when get passed # to this routine which also have their f_trace set to None. # This will disallow a command like "jump" from working properly, # which will give a cryptic the message on setting f_lineno: # f_lineno can only be set by a trace function if self.ignore_filter and self.ignore_filter.is_included(frame): return True if self.debugger.settings['trace']: print_event_set = self.debugger.settings['printset'] if self.event in print_event_set: self.trace_processor.event_processor(frame, self.event, arg) pass pass if self.until_condition: if not self.matches_condition(frame): return True pass trace_event_set = self.debugger.settings['events'] if trace_event_set is None or self.event not in trace_event_set: return True # I think we *have* to run is_stop_here() before # is_break_here() because is_stop_here() sets various # stepping counts. But it might be more desirable from the # user's standpoint to test for breaks before steps. In # this case we will need to factor out the counting # updates. if ( self.is_stop_here(frame, event, arg) or self.is_break_here(frame, arg) ): # Run the event processor return self.processor.event_processor(frame, self.event, arg) return True finally: try: self.debugger_lock.release() except: pass pass pass
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/core.py#L392-L451
[ "def", "trace_dispatch", "(", "self", ",", "frame", ",", "event", ",", "arg", ")", ":", "# For now we only allow one instance in a process", "# In Python 2.6 and beyond one can use \"with threading.Lock():\"", "try", ":", "self", ".", "debugger_lock", ".", "acquire", "(", ")", "if", "self", ".", "trace_hook_suspend", ":", "return", "None", "self", ".", "event", "=", "event", "# FIXME: Understand what's going on here better.", "# When None gets returned, the frame's f_trace seems to get set", "# to None. Somehow this is changing other frames when get passed", "# to this routine which also have their f_trace set to None.", "# This will disallow a command like \"jump\" from working properly,", "# which will give a cryptic the message on setting f_lineno:", "# f_lineno can only be set by a trace function", "if", "self", ".", "ignore_filter", "and", "self", ".", "ignore_filter", ".", "is_included", "(", "frame", ")", ":", "return", "True", "if", "self", ".", "debugger", ".", "settings", "[", "'trace'", "]", ":", "print_event_set", "=", "self", ".", "debugger", ".", "settings", "[", "'printset'", "]", "if", "self", ".", "event", "in", "print_event_set", ":", "self", ".", "trace_processor", ".", "event_processor", "(", "frame", ",", "self", ".", "event", ",", "arg", ")", "pass", "pass", "if", "self", ".", "until_condition", ":", "if", "not", "self", ".", "matches_condition", "(", "frame", ")", ":", "return", "True", "pass", "trace_event_set", "=", "self", ".", "debugger", ".", "settings", "[", "'events'", "]", "if", "trace_event_set", "is", "None", "or", "self", ".", "event", "not", "in", "trace_event_set", ":", "return", "True", "# I think we *have* to run is_stop_here() before", "# is_break_here() because is_stop_here() sets various", "# stepping counts. But it might be more desirable from the", "# user's standpoint to test for breaks before steps. In", "# this case we will need to factor out the counting", "# updates.", "if", "(", "self", ".", "is_stop_here", "(", "frame", ",", "event", ",", "arg", ")", "or", "self", ".", "is_break_here", "(", "frame", ",", "arg", ")", ")", ":", "# Run the event processor", "return", "self", ".", "processor", ".", "event_processor", "(", "frame", ",", "self", ".", "event", ",", "arg", ")", "return", "True", "finally", ":", "try", ":", "self", ".", "debugger_lock", ".", "release", "(", ")", "except", ":", "pass", "pass", "pass" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
InfoThread.stack_trace
A mini stack trace routine for threads.
trepan/processor/command/info_subcmd/threads.py
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) pass f = f.f_back pass return
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) pass f = f.f_back pass return
[ "A", "mini", "stack", "trace", "routine", "for", "threads", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/info_subcmd/threads.py#L55-L65
[ "def", "stack_trace", "(", "self", ",", "f", ")", ":", "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", ")", "pass", "f", "=", "f", ".", "f_back", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
InfoFiles.run
Get file information
trepan/processor/command/info_subcmd/files.py
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] pass m = filename + ' is' filename_cache = self.core.filename_cache if filename in filename_cache: m += " cached in debugger" if filename_cache[filename] != filename: m += ' as:' m = Mmisc.wrapped_lines(m, filename_cache[filename] + '.', self.settings['width']) else: m += '.' pass self.msg(m) else: matches = [file for file in file_list() if file.endswith(filename)] if (len(matches) > 1): self.msg("Multiple files found ending filename string:") for match_file in matches: self.msg("\t%s" % match_file) pass elif len(matches) == 1: canonic_name = pyficache.unmap_file(matches[0]) m += " matched debugger cache file:\n " + canonic_name self.msg(m) else: self.msg(m + ' not cached in debugger.') pass canonic_name = self.core.canonic(filename) self.msg(Mmisc.wrapped_lines('Canonic name:', canonic_name, self.settings['width'])) for name in (canonic_name, filename): if name in sys.modules: for key in [k for k, v in list(sys.modules.items()) if name == v]: self.msg("module: %s", key) pass pass pass for arg in args[1:]: processed_arg = False if arg in ['all', 'size']: if pyficache.size(canonic_name): self.msg("File has %d lines." % pyficache.size(canonic_name)) pass processed_arg = True pass if arg in ['all', 'sha1']: self.msg("SHA1 is %s." % pyficache.sha1(canonic_name)) processed_arg = True pass if arg in ['all', 'brkpts']: lines = pyficache.trace_line_numbers(canonic_name) if lines: self.section("Possible breakpoint line numbers:") fmt_lines = columnize.columnize(lines, ljust = False, arrange_vertical = False, lineprefix=' ') self.msg(fmt_lines) pass processed_arg = True pass if not processed_arg: self.errmsg("Don't understand sub-option %s." % arg) pass pass return
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] pass m = filename + ' is' filename_cache = self.core.filename_cache if filename in filename_cache: m += " cached in debugger" if filename_cache[filename] != filename: m += ' as:' m = Mmisc.wrapped_lines(m, filename_cache[filename] + '.', self.settings['width']) else: m += '.' pass self.msg(m) else: matches = [file for file in file_list() if file.endswith(filename)] if (len(matches) > 1): self.msg("Multiple files found ending filename string:") for match_file in matches: self.msg("\t%s" % match_file) pass elif len(matches) == 1: canonic_name = pyficache.unmap_file(matches[0]) m += " matched debugger cache file:\n " + canonic_name self.msg(m) else: self.msg(m + ' not cached in debugger.') pass canonic_name = self.core.canonic(filename) self.msg(Mmisc.wrapped_lines('Canonic name:', canonic_name, self.settings['width'])) for name in (canonic_name, filename): if name in sys.modules: for key in [k for k, v in list(sys.modules.items()) if name == v]: self.msg("module: %s", key) pass pass pass for arg in args[1:]: processed_arg = False if arg in ['all', 'size']: if pyficache.size(canonic_name): self.msg("File has %d lines." % pyficache.size(canonic_name)) pass processed_arg = True pass if arg in ['all', 'sha1']: self.msg("SHA1 is %s." % pyficache.sha1(canonic_name)) processed_arg = True pass if arg in ['all', 'brkpts']: lines = pyficache.trace_line_numbers(canonic_name) if lines: self.section("Possible breakpoint line numbers:") fmt_lines = columnize.columnize(lines, ljust = False, arrange_vertical = False, lineprefix=' ') self.msg(fmt_lines) pass processed_arg = True pass if not processed_arg: self.errmsg("Don't understand sub-option %s." % arg) pass pass return
[ "Get", "file", "information" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/info_subcmd/files.py#L51-L128
[ "def", "run", "(", "self", ",", "args", ")", ":", "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", "]", "pass", "m", "=", "filename", "+", "' is'", "filename_cache", "=", "self", ".", "core", ".", "filename_cache", "if", "filename", "in", "filename_cache", ":", "m", "+=", "\" cached in debugger\"", "if", "filename_cache", "[", "filename", "]", "!=", "filename", ":", "m", "+=", "' as:'", "m", "=", "Mmisc", ".", "wrapped_lines", "(", "m", ",", "filename_cache", "[", "filename", "]", "+", "'.'", ",", "self", ".", "settings", "[", "'width'", "]", ")", "else", ":", "m", "+=", "'.'", "pass", "self", ".", "msg", "(", "m", ")", "else", ":", "matches", "=", "[", "file", "for", "file", "in", "file_list", "(", ")", "if", "file", ".", "endswith", "(", "filename", ")", "]", "if", "(", "len", "(", "matches", ")", ">", "1", ")", ":", "self", ".", "msg", "(", "\"Multiple files found ending filename string:\"", ")", "for", "match_file", "in", "matches", ":", "self", ".", "msg", "(", "\"\\t%s\"", "%", "match_file", ")", "pass", "elif", "len", "(", "matches", ")", "==", "1", ":", "canonic_name", "=", "pyficache", ".", "unmap_file", "(", "matches", "[", "0", "]", ")", "m", "+=", "\" matched debugger cache file:\\n \"", "+", "canonic_name", "self", ".", "msg", "(", "m", ")", "else", ":", "self", ".", "msg", "(", "m", "+", "' not cached in debugger.'", ")", "pass", "canonic_name", "=", "self", ".", "core", ".", "canonic", "(", "filename", ")", "self", ".", "msg", "(", "Mmisc", ".", "wrapped_lines", "(", "'Canonic name:'", ",", "canonic_name", ",", "self", ".", "settings", "[", "'width'", "]", ")", ")", "for", "name", "in", "(", "canonic_name", ",", "filename", ")", ":", "if", "name", "in", "sys", ".", "modules", ":", "for", "key", "in", "[", "k", "for", "k", ",", "v", "in", "list", "(", "sys", ".", "modules", ".", "items", "(", ")", ")", "if", "name", "==", "v", "]", ":", "self", ".", "msg", "(", "\"module: %s\"", ",", "key", ")", "pass", "pass", "pass", "for", "arg", "in", "args", "[", "1", ":", "]", ":", "processed_arg", "=", "False", "if", "arg", "in", "[", "'all'", ",", "'size'", "]", ":", "if", "pyficache", ".", "size", "(", "canonic_name", ")", ":", "self", ".", "msg", "(", "\"File has %d lines.\"", "%", "pyficache", ".", "size", "(", "canonic_name", ")", ")", "pass", "processed_arg", "=", "True", "pass", "if", "arg", "in", "[", "'all'", ",", "'sha1'", "]", ":", "self", ".", "msg", "(", "\"SHA1 is %s.\"", "%", "pyficache", ".", "sha1", "(", "canonic_name", ")", ")", "processed_arg", "=", "True", "pass", "if", "arg", "in", "[", "'all'", ",", "'brkpts'", "]", ":", "lines", "=", "pyficache", ".", "trace_line_numbers", "(", "canonic_name", ")", "if", "lines", ":", "self", ".", "section", "(", "\"Possible breakpoint line numbers:\"", ")", "fmt_lines", "=", "columnize", ".", "columnize", "(", "lines", ",", "ljust", "=", "False", ",", "arrange_vertical", "=", "False", ",", "lineprefix", "=", "' '", ")", "self", ".", "msg", "(", "fmt_lines", ")", "pass", "processed_arg", "=", "True", "pass", "if", "not", "processed_arg", ":", "self", ".", "errmsg", "(", "\"Don't understand sub-option %s.\"", "%", "arg", ")", "pass", "pass", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
NextCommand.run
**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 suffix of `+` on the command or an alias to the command forces to move to another line, while a suffix of `-` does the opposite and disables the requiring a move to a new line. If no suffix is given, the debugger setting 'different-line' determines this behavior. See also: --------- `step`, `skip`, `jump` (there's no `hop` yet), `continue`, and `finish` for other ways to progress execution.
trepan/processor/command/next.py
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 suffix of `+` on the command or an alias to the command forces to move to another line, while a suffix of `-` does the opposite and disables the requiring a move to a new line. If no suffix is given, the debugger setting 'different-line' determines this behavior. See also: --------- `step`, `skip`, `jump` (there's no `hop` yet), `continue`, and `finish` for other ways to progress execution. """ if len(args) <= 1: step_ignore = 0 else: step_ignore = self.proc.get_int(args[1], default=1, cmdname='next') if step_ignore is None: return False # 0 means stop now or step 1, so we subtract 1. step_ignore -= 1 pass self.core.different_line = \ Mcmdfns.want_different_line(args[0], self.debugger.settings['different']) self.core.set_next(self.proc.frame, step_ignore) self.proc.continue_running = True # Break out of command read loop return True
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 suffix of `+` on the command or an alias to the command forces to move to another line, while a suffix of `-` does the opposite and disables the requiring a move to a new line. If no suffix is given, the debugger setting 'different-line' determines this behavior. See also: --------- `step`, `skip`, `jump` (there's no `hop` yet), `continue`, and `finish` for other ways to progress execution. """ if len(args) <= 1: step_ignore = 0 else: step_ignore = self.proc.get_int(args[1], default=1, cmdname='next') if step_ignore is None: return False # 0 means stop now or step 1, so we subtract 1. step_ignore -= 1 pass self.core.different_line = \ Mcmdfns.want_different_line(args[0], self.debugger.settings['different']) self.core.set_next(self.proc.frame, step_ignore) self.proc.continue_running = True # Break out of command read loop return True
[ "**", "next", "**", "[", "**", "+", "**", "|", "**", "-", "**", "]", "[", "*", "count", "*", "]" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/processor/command/next.py#L35-L70
[ "def", "run", "(", "self", ",", "args", ")", ":", "if", "len", "(", "args", ")", "<=", "1", ":", "step_ignore", "=", "0", "else", ":", "step_ignore", "=", "self", ".", "proc", ".", "get_int", "(", "args", "[", "1", "]", ",", "default", "=", "1", ",", "cmdname", "=", "'next'", ")", "if", "step_ignore", "is", "None", ":", "return", "False", "# 0 means stop now or step 1, so we subtract 1.", "step_ignore", "-=", "1", "pass", "self", ".", "core", ".", "different_line", "=", "Mcmdfns", ".", "want_different_line", "(", "args", "[", "0", "]", ",", "self", ".", "debugger", ".", "settings", "[", "'different'", "]", ")", "self", ".", "core", ".", "set_next", "(", "self", ".", "proc", ".", "frame", ",", "step_ignore", ")", "self", ".", "proc", ".", "continue_running", "=", "True", "# Break out of command read loop", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
checkfuncname
Check whether we should break here because of `b.funcname`.
trepan/lib/breakpoint.py
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: don't break. return False return True # Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False # We are in the right frame. if not b.func_first_executable_line: # The function is entered for the 1st time. b.func_first_executable_line = frame.f_lineno if b.func_first_executable_line != frame.f_lineno: # But we are not at the first line number: don't break. return False return True
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: don't break. return False return True # Breakpoint set via function name. if frame.f_code.co_name != b.funcname: # It's not a function call, but rather execution of def statement. return False # We are in the right frame. if not b.func_first_executable_line: # The function is entered for the 1st time. b.func_first_executable_line = frame.f_lineno if b.func_first_executable_line != frame.f_lineno: # But we are not at the first line number: don't break. return False return True
[ "Check", "whether", "we", "should", "break", "here", "because", "of", "b", ".", "funcname", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L291-L315
[ "def", "checkfuncname", "(", "b", ",", "frame", ")", ":", "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: don't break.", "return", "False", "return", "True", "# Breakpoint set via function name.", "if", "frame", ".", "f_code", ".", "co_name", "!=", "b", ".", "funcname", ":", "# It's not a function call, but rather execution of def statement.", "return", "False", "# We are in the right frame.", "if", "not", "b", ".", "func_first_executable_line", ":", "# The function is entered for the 1st time.", "b", ".", "func_first_executable_line", "=", "frame", ".", "f_lineno", "if", "b", ".", "func_first_executable_line", "!=", "frame", ".", "f_lineno", ":", "# But we are not at the first line number: don't break.", "return", "False", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BreakpointManager.delete_breakpoint
remove breakpoint `bp
trepan/lib/breakpoint.py
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]: # No more breakpoints for this file:line combo del self.bplist[index] return True
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]: # No more breakpoints for this file:line combo del self.bplist[index] return True
[ "remove", "breakpoint", "bp" ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L83-L93
[ "def", "delete_breakpoint", "(", "self", ",", "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", "]", ":", "# No more breakpoints for this file:line combo", "del", "self", ".", "bplist", "[", "index", "]", "return", "True" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BreakpointManager.delete_breakpoint_by_number
Remove a breakpoint given its breakpoint number.
trepan/lib/breakpoint.py
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, '')
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, '')
[ "Remove", "a", "breakpoint", "given", "its", "breakpoint", "number", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L95-L101
[ "def", "delete_breakpoint_by_number", "(", "self", ",", "bpnum", ")", ":", "success", ",", "msg", ",", "bp", "=", "self", ".", "get_breakpoint", "(", "bpnum", ")", "if", "not", "success", ":", "return", "False", ",", "msg", "self", ".", "delete_breakpoint", "(", "bp", ")", "return", "(", "True", ",", "''", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BreakpointManager.en_disable_all_breakpoints
Enable or disable all breakpoints.
trepan/lib/breakpoint.py
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: return "No breakpoints to %sable" % endis for bp in bp_list: bp.enabled = do_enable bp_nums.append(str(bp.number)) pass return ("Breakpoints %sabled: %s" % (endis, ", ".join(bp_nums)))
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: return "No breakpoints to %sable" % endis for bp in bp_list: bp.enabled = do_enable bp_nums.append(str(bp.number)) pass return ("Breakpoints %sabled: %s" % (endis, ", ".join(bp_nums)))
[ "Enable", "or", "disable", "all", "breakpoints", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L103-L118
[ "def", "en_disable_all_breakpoints", "(", "self", ",", "do_enable", "=", "True", ")", ":", "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", ":", "return", "\"No breakpoints to %sable\"", "%", "endis", "for", "bp", "in", "bp_list", ":", "bp", ".", "enabled", "=", "do_enable", "bp_nums", ".", "append", "(", "str", "(", "bp", ".", "number", ")", ")", "pass", "return", "(", "\"Breakpoints %sabled: %s\"", "%", "(", "endis", ",", "\", \"", ".", "join", "(", "bp_nums", ")", ")", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BreakpointManager.en_disable_breakpoint_by_number
Enable or disable a breakpoint given its breakpoint number.
trepan/lib/breakpoint.py
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: endis = 'dis' pass if bp.enabled == do_enable: return (False, ('Breakpoint (%r) previously %sabled' % (str(bpnum), endis,))) bp.enabled = do_enable return (True, '')
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: endis = 'dis' pass if bp.enabled == do_enable: return (False, ('Breakpoint (%r) previously %sabled' % (str(bpnum), endis,))) bp.enabled = do_enable return (True, '')
[ "Enable", "or", "disable", "a", "breakpoint", "given", "its", "breakpoint", "number", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L120-L134
[ "def", "en_disable_breakpoint_by_number", "(", "self", ",", "bpnum", ",", "do_enable", "=", "True", ")", ":", "success", ",", "msg", ",", "bp", "=", "self", ".", "get_breakpoint", "(", "bpnum", ")", "if", "not", "success", ":", "return", "success", ",", "msg", "if", "do_enable", ":", "endis", "=", "'en'", "else", ":", "endis", "=", "'dis'", "pass", "if", "bp", ".", "enabled", "==", "do_enable", ":", "return", "(", "False", ",", "(", "'Breakpoint (%r) previously %sabled'", "%", "(", "str", "(", "bpnum", ")", ",", "endis", ",", ")", ")", ")", "bp", ".", "enabled", "=", "do_enable", "return", "(", "True", ",", "''", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BreakpointManager.delete_breakpoints_by_lineno
Removes all breakpoints at a give filename and line number. Returns a list of breakpoints numbers deleted.
trepan/lib/breakpoint.py
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)] bpnums = [bp.number for bp in breakpoints] for bp in list(breakpoints): self.delete_breakpoint(bp) return bpnums
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)] bpnums = [bp.number for bp in breakpoints] for bp in list(breakpoints): self.delete_breakpoint(bp) return bpnums
[ "Removes", "all", "breakpoints", "at", "a", "give", "filename", "and", "line", "number", ".", "Returns", "a", "list", "of", "breakpoints", "numbers", "deleted", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L136-L146
[ "def", "delete_breakpoints_by_lineno", "(", "self", ",", "filename", ",", "lineno", ")", ":", "if", "(", "filename", ",", "lineno", ")", "not", "in", "self", ".", "bplist", ":", "return", "[", "]", "breakpoints", "=", "self", ".", "bplist", "[", "(", "filename", ",", "lineno", ")", "]", "bpnums", "=", "[", "bp", ".", "number", "for", "bp", "in", "breakpoints", "]", "for", "bp", "in", "list", "(", "breakpoints", ")", ":", "self", ".", "delete_breakpoint", "(", "bp", ")", "return", "bpnums" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
BreakpointManager.find_bp
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.
trepan/lib/breakpoint.py
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. """ possibles = self.bplist[filename, lineno] for i in range(0, len(possibles)): b = possibles[i] if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.condition: # If unconditional, and ignoring, go on to next, else # break if b.ignore > 0: b.ignore = b.ignore -1 continue else: # breakpoint and marker that's ok to delete if # temporary return (b, True) else: # Conditional bp. # Ignore count applies only to those bpt hits where the # condition evaluates to true. try: val = eval(b.condition, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore = b.ignore -1 # continue else: return (b, True) # else: # continue except: # if eval fails, most conservative thing is to # stop on breakpoint regardless of ignore count. # Don't delete temporary, as another hint to user. return (b, False) pass pass return (None, None)
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. """ possibles = self.bplist[filename, lineno] for i in range(0, len(possibles)): b = possibles[i] if not b.enabled: continue if not checkfuncname(b, frame): continue # Count every hit when bp is enabled b.hits += 1 if not b.condition: # If unconditional, and ignoring, go on to next, else # break if b.ignore > 0: b.ignore = b.ignore -1 continue else: # breakpoint and marker that's ok to delete if # temporary return (b, True) else: # Conditional bp. # Ignore count applies only to those bpt hits where the # condition evaluates to true. try: val = eval(b.condition, frame.f_globals, frame.f_locals) if val: if b.ignore > 0: b.ignore = b.ignore -1 # continue else: return (b, True) # else: # continue except: # if eval fails, most conservative thing is to # stop on breakpoint regardless of ignore count. # Don't delete temporary, as another hint to user. return (b, False) pass pass return (None, None)
[ "Determine", "which", "breakpoint", "for", "this", "file", ":", "line", "is", "to", "be", "acted", "upon", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/lib/breakpoint.py#L148-L196
[ "def", "find_bp", "(", "self", ",", "filename", ",", "lineno", ",", "frame", ")", ":", "possibles", "=", "self", ".", "bplist", "[", "filename", ",", "lineno", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "possibles", ")", ")", ":", "b", "=", "possibles", "[", "i", "]", "if", "not", "b", ".", "enabled", ":", "continue", "if", "not", "checkfuncname", "(", "b", ",", "frame", ")", ":", "continue", "# Count every hit when bp is enabled", "b", ".", "hits", "+=", "1", "if", "not", "b", ".", "condition", ":", "# If unconditional, and ignoring, go on to next, else", "# break", "if", "b", ".", "ignore", ">", "0", ":", "b", ".", "ignore", "=", "b", ".", "ignore", "-", "1", "continue", "else", ":", "# breakpoint and marker that's ok to delete if", "# temporary", "return", "(", "b", ",", "True", ")", "else", ":", "# Conditional bp.", "# Ignore count applies only to those bpt hits where the", "# condition evaluates to true.", "try", ":", "val", "=", "eval", "(", "b", ".", "condition", ",", "frame", ".", "f_globals", ",", "frame", ".", "f_locals", ")", "if", "val", ":", "if", "b", ".", "ignore", ">", "0", ":", "b", ".", "ignore", "=", "b", ".", "ignore", "-", "1", "# continue", "else", ":", "return", "(", "b", ",", "True", ")", "# else:", "# continue", "except", ":", "# if eval fails, most conservative thing is to", "# stop on breakpoint regardless of ignore count.", "# Don't delete temporary, as another hint to user.", "return", "(", "b", ",", "False", ")", "pass", "pass", "return", "(", "None", ",", "None", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
ScriptInput.open
Use this to set what file to read from.
trepan/inout/scriptin.py
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: raise IOError("Invalid input type (%s) for %s" % (inp.__class__.__name__, inp)) return
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: raise IOError("Invalid input type (%s) for %s" % (inp.__class__.__name__, inp)) return
[ "Use", "this", "to", "set", "what", "file", "to", "read", "from", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/scriptin.py#L41-L51
[ "def", "open", "(", "self", ",", "inp", ",", "opts", "=", "None", ")", ":", "if", "isinstance", "(", "inp", ",", "io", ".", "TextIOWrapper", ")", ":", "self", ".", "input", "=", "inp", "elif", "isinstance", "(", "inp", ",", "'string'", ".", "__class__", ")", ":", "# FIXME", "self", ".", "name", "=", "inp", "self", ".", "input", "=", "open", "(", "inp", ",", "'r'", ")", "else", ":", "raise", "IOError", "(", "\"Invalid input type (%s) for %s\"", "%", "(", "inp", ".", "__class__", ".", "__name__", ",", "inp", ")", ")", "return" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3
test
ScriptInput.readline
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.
trepan/inout/scriptin.py
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.rstrip("\n")
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.rstrip("\n")
[ "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", "." ]
rocky/python3-trepan
python
https://github.com/rocky/python3-trepan/blob/14e91bc0acce090d67be145b1ac040cab92ac5f3/trepan/inout/scriptin.py#L53-L60
[ "def", "readline", "(", "self", ",", "prompt", "=", "''", ",", "use_raw", "=", "None", ")", ":", "line", "=", "self", ".", "input", ".", "readline", "(", ")", "if", "not", "line", ":", "raise", "EOFError", "return", "line", ".", "rstrip", "(", "\"\\n\"", ")" ]
14e91bc0acce090d67be145b1ac040cab92ac5f3