Ejemplo n.º 1
0
def _main():
    """Run from command line."""
    usage = "usage: %prog [options] cmd [arg] ..."
    optprs = OptionParser(usage=usage, version=version)

    optprs.add_option("--debug", dest="debug", default=False,
                      action="store_true",
                      help="Enter the pdb debugger on main()")
    optprs.add_option("--host", dest="host", metavar="HOST",
                      default="localhost", help="Connect to server at HOST")
    optprs.add_option("--port", dest="port", type="int",
                      default=9000, metavar="PORT",
                      help="Connect to server at PORT")
    optprs.add_option("--profile", dest="profile", action="store_true",
                      default=False,
                      help="Run the profiler on main()")

    (options, args) = optprs.parse_args(sys.argv[1:])

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print("%s profile:" % sys.argv[0])
        profile.run('main(options, args)')

    else:
        main(options, args)
Ejemplo n.º 2
0
def user_main(args, exit_code=False):
    """Call one of the multiple main() functions based on environment variables.

    :param args: command line arguments passed into yum
    :param exit_code: if *exit_code* is True, this function will exit
       python with its exit code when it has finished executing.
       Otherwise, it will return its exit code.
    :return: the exit code from yum execution
    """
    errcode = None
    if "YUM_PROF" in os.environ:
        if os.environ["YUM_PROF"] == "cprof":
            errcode = cprof(main, args)
        if os.environ["YUM_PROF"] == "hotshot":
            errcode = hotshot(main, args)
    if "YUM_PDB" in os.environ:
        import pdb

        pdb.run(main(args))

    if errcode is None:
        errcode = main(args)
    if exit_code:
        sys.exit(errcode)
    return errcode
Ejemplo n.º 3
0
def planner(sys_argv):

    viewer = QueuePlanner(layout=default_layout)
    viewer.add_plugins(plugins)

    # Parse command line options with optparse module
    from optparse import OptionParser

    usage = "usage: %prog [options] cmd [args]"
    optprs = OptionParser(usage=usage,
                          version=('%%prog %s' % version.version))
    viewer.add_default_options(optprs)

    (options, args) = optprs.parse_args(sys_argv[1:])

    if options.display:
        os.environ['DISPLAY'] = options.display

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('viewer.main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys_argv[0]))
        profile.run('viewer.main(options, args)')

    else:
        viewer.main(options, args)
Ejemplo n.º 4
0
def main():
    settings = None
    try:
        meta, settings, profile, debug, benchmarks, name, port = setup()

        while True:
            data = ui.main(meta, settings)

            if data is None:
                break

            if data['local']:
                # Local Server
                server_obj = server_interface.LocalInterface(name, data['save'], port, settings)
            else:
                # Remote Server
                server_obj = server_interface.RemoteInterface(name, data['ip'], data['port'])

            if not server_obj.error:
                render_interface.setup_render_module(settings)

                if profile:
                    cProfile.runctx('game(server_obj, settings, benchmarks)', globals(), locals(), filename='game.profile')
                elif debug:
                    pdb.run('game(server_obj, settings, benchmarks)', globals(), locals())
                else:
                    game(server_obj, settings, benchmarks)

            if server_obj.error:
                ui.error(server_obj.error)

    finally:
        setdown()
Ejemplo n.º 5
0
def reference_viewer(sys_argv):
    """Create reference viewer from command line."""
    viewer = ReferenceViewer(layout=default_layout)
    viewer.add_default_plugins()
    viewer.add_separately_distributed_plugins()

    # Parse command line options with optparse module
    from optparse import OptionParser

    usage = "usage: %prog [options] cmd [args]"
    optprs = OptionParser(usage=usage,
                          version=('%%prog %s' % version.version))
    viewer.add_default_options(optprs)

    (options, args) = optprs.parse_args(sys_argv[1:])

    if options.display:
        os.environ['DISPLAY'] = options.display

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('viewer.main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys_argv[0]))
        profile.run('viewer.main(options, args)')

    else:
        viewer.main(options, args)
Ejemplo n.º 6
0
def debug(module, name):
    """Debug a single docstring containing doctests.

    Provide the module (or dotted name of the module) containing the
    docstring to be debugged, and the name (within the module) of the
    object with the docstring to be debugged.

    The doctest examples are extracted (see function testsource()),
    and written to a temp file.  The Python debugger (pdb) is then
    invoked on that file.
    """

    import os
    import pdb
    import tempfile

    module = _normalize_module(module)
    testsrc = testsource(module, name)
    srcfilename = tempfile.mktemp("doctestdebug.py")
    f = file(srcfilename, 'w')
    f.write(testsrc)
    f.close()

    globs = {}
    globs.update(module.__dict__)
    try:
        # Note that %r is vital here.  '%s' instead can, e.g., cause
        # backslashes to get treated as metacharacters on Windows.
        pdb.run("execfile(%r)" % srcfilename, globs, globs)
    finally:
        os.remove(srcfilename)
Ejemplo n.º 7
0
    def exec(node, intf, packet, barrier):
        pktlib = __import__('switchyard.lib.packet', fromlist=('packet',))
        xlocals = {'packet':packet, 'pktlib':pktlib,'EthAddr':EthAddr,'IPAddr':IPAddr}
        print ("Debugging packet object on receive at {}:{}".format(node, intf))
        debugstmt = '''
# Nonstatement to get into the debugger
'''
        pdb.run(debugstmt, globals={}, locals=xlocals)
        barrier.wait()
Ejemplo n.º 8
0
def run(command):
	# Save Maya's current stdin and stdout.
	orig_stdin = sys.stdin
	orig_stdout = sys.stdout

	# Replace stdin and stdout with instances of our own classes.
	sys.stdin = DebuggerStandardInput()

	# Run pdb.
	pdb.run(command)

	# Restore Maya's original stdin and stdout.
	sys.stdin = orig_stdin
	sys.stdout = orig_stdout
Ejemplo n.º 9
0
    def run_script(self, obj=None, top=None, param=None,
                         wdir=None, app=None, model=None,
                         **kargs):


           
       script_file = obj.path2fullpath()
       logging.basicConfig(level=logging.DEBUG)
       if script_file == '':return

       if (os.path.getmtime(script_file) >
            self._script_mtime):
            self.load_script(script_file)
       if self._script_co is not None:
          debug = self._debug
          def write_log(*args):
              top.write_log(obj, model, *args)

          lc = obj.get_namespace()
          lc2 = {"obj":obj, "proj":top, "top":top,  "param":param,
                "wdir":wdir, "app":app, "model":model,  "stop":stop,
                "exit":exit, "write_log": write_log}
          for key in lc2: lc[key] = lc2[key]          
          for key in kargs: lc[key] = kargs[key]

          self._debug = 0  ### make sure that next time will run in normal mode
          try:
              if debug == 0:
                  exec self._script_co in lc, lc 
              elif debug == 1:
                  import pdb
                  pdb.run(self._script_co, lc, lc )
              elif debug == 2:
                  app.script_editor.RunSED(self._script_co, lc, lc, script_file)

          except ExitScript:
              return True
          except ScriptStop as e:
              print('Script execution stops : ', e.message)
              return False
          except Exception:
              print('script exectuion failed')
              print(traceback.format_exc())
              return False
              #logging.exception("Script Execution Failed")
          return True
Ejemplo n.º 10
0
def user_main(args, exit_code=False):
    """ This calls one of the multiple main() functions based on env. vars """
    errcode = None
    if 'YUM_PROF' in os.environ:
        if os.environ['YUM_PROF'] == 'cprof':
            errcode = cprof(main, args)
        if os.environ['YUM_PROF'] == 'hotshot':
            errcode = hotshot(main, args)
    if 'YUM_PDB' in os.environ:
        import pdb
        pdb.run(main(args))

    if errcode is None:
        errcode = main(args)
    if exit_code:
        sys.exit(errcode)
    return errcode
Ejemplo n.º 11
0
def main(argv):
    """
    call vsfh.run_parallel with command line options and set up logger.
    """
    parser = argparse.ArgumentParser(description="Run trilegal many times by \
                                     randomly sampling SFH uncertainies")

    parser.add_argument('-d', '--dry_run', action='store_true',
                        help='do not call trilegal')

    parser.add_argument('-v', '--pdb', action='store_true',
                        help='debugging mode')

    parser.add_argument('-n', '--nproc', type=int, default=8,
                        help='number of processors')

    parser.add_argument('-c', '--cleanup', action='store_true',
                        help='remove large files when finished')

    parser.add_argument('name', type=str, help='input file')

    args = parser.parse_args(argv)

    # set up logging
    handler = logging.FileHandler('{}_vary_sfh.log'.format(args.name))
    if args.pdb:
        handler.setLevel(logging.DEBUG)
    else:
        handler.setLevel(logging.INFO)
    formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
    handler.setFormatter(formatter)
    logger.addHandler(handler)

    inp_obj = rsp.fileio.InputParameters(default_dict=initialize_inputs())
    inp_obj.input_file = args.name
    inp_obj.add_params(rsp.fileio.load_input(inp_obj.input_file), loud=args.pdb)

    vsh = VarySFHs(inp_obj=inp_obj)
    if args.pdb:
        import pdb
        pdb.run(vsh.run_parallel(dry_run=args.dry_run, max_proc=args.nproc,
                                 cleanup=args.cleanup))
    else:
        vsh.run_parallel(dry_run=args.dry_run, max_proc=args.nproc,
                         cleanup=args.cleanup)
Ejemplo n.º 12
0
 def run(self):
     if self.input:
         try:
             # noinspection PyUnresolvedReferences
             import pstats
         except ImportError:
             display('Module pstats not found.', color=RED)
             return
         if not os.path.isfile(self.input):
             display(u('File %s not found' % self.input), color=RED)
             return
         stats = pstats.Stats(self.input)
         stats.print_stats()
     elif not self.call:
         display('Please provide a function to profile with --call \'module.function\'', color=RED)
         return
     else:
         if '(' not in self.call:
             self.call += '()'
         tokens = tokenize.generate_tokens(BytesIO(self.call).readline)
         index = 0
         simple_function_call = True
         for toknum, tokval, tokstart, tokend, tokline in tokens:
             if toknum == token.ENDMARKER:
                 break
             elif index == 0 and toknum != token.NAME:
                 simple_function_call = False
                 break
             elif index == 1 and toknum == token.OP and tokval == '(':
                 break
             elif index == 1 and (toknum != token.OP or tokval != '.'):
                 simple_function_call = False
                 break
             index = 1 - index
         if simple_function_call:
             module_name = self.call.partition('(')[0].rpartition('.')[0]
             if module_name:
                 display('Load module %s' % module_name, color=GREEN)
                 self.call = 'import %s ; %s' % (module_name, self.call)
         display("running profiling on %(call)s" % {'call': self.call}, color=GREEN)
         if self.debug:
             pdb.run(self.call)
         else:
             profile.run(self.call, self.output)
Ejemplo n.º 13
0
 def run(self):
     if self.input:
         try:
             # noinspection PyUnresolvedReferences
             import pstats
         except ImportError:
             logging.error("Module pstats not found.")
             return
         if not os.path.isfile(self.input):
             logging.error(py3k_unicode("File %s not found" % self.input))
             return
         stats = pstats.Stats(self.input)
         stats.print_stats()
     elif not self.call:
         logging.error("Please provide a function to profile with --call 'module.function'")
         return
     else:
         if "(" not in self.call:
             self.call += "()"
         tokens = tokenize.generate_tokens(BytesIO(self.call).readline)
         index = 0
         simple_function_call = True
         for toknum, tokval, tokstart, tokend, tokline in tokens:
             if toknum == token.ENDMARKER:
                 break
             elif index == 0 and toknum != token.NAME:
                 simple_function_call = False
                 break
             elif index == 1 and toknum == token.OP and tokval == "(":
                 break
             elif index == 1 and (toknum != token.OP or tokval != "."):
                 simple_function_call = False
                 break
             index = 1 - index
         if simple_function_call:
             module_name = self.call.partition("(")[0].rpartition(".")[0]
             if module_name:
                 logging.info("Load module %s" % module_name)
                 self.call = "import %s ; %s" % (module_name, self.call)
         logging.info("running profiling on %(call)s" % {"call": self.call})
         if self.debug:
             pdb.run(self.call)
         else:
             profile.run(self.call, self.output)
Ejemplo n.º 14
0
def main():

	# Parse command line args
	debug = False
	run = False
	if len(sys.argv) == 2:
		
		if sys.argv[1] == "help":
			print("To run, please enter \"python3 main.py\"! No args needed.")
			print("And please make sure you have all the necessary packages installed.")
		
		if sys.argv[1] == "run_tests":
			# Run tests for analyze_language.py (Rebecca)
			test = t_al.AnalyzeLanguageTest()
			test.ALTest()
			test.RATest()
			test.WordInfoTest()
			test.SentInfoTest()
			test.ParagInfoTest()
			test.ContentInfoTest()
			test.SentimentInfoTest()
			test.POSTest()
			object = score_test.AnalyzeScoreTest()
			object.GeneralScoreTest()
			object.SubredditScoreTest()



		if sys.argv[1] == "debug":
			print("Running in debug:")
			debug = True
			run = True

	if len(sys.argv) == 1:
		run = True

	if run:
		
		if debug:
			pdb.run("run_program()")
		else:
			run_program()
Ejemplo n.º 15
0
    def run(cls, cmdlineargs, *args, **kwargs):
        # print cls
        cls._options = filter(
            lambda x: isinstance(x, CmdLineOption), map(lambda x: eval("cls." + x, {"cls": cls}), dir(cls))
        )
        do_parse_options(cls.ProgramMetadata, cls._options)
        setprocname(sys.argv[0].split("/")[-1])
        if int(cls.debugger_option.value):
            if int(cls.debugger_option.value) == 1:
                import pdb

                try:
                    pdb.run("cls.prepare_process()", globals(), {"cls": cls})
                    pdb.run("cls.process()", globals(), {"cls": cls})
                    pdb.run("cls.finish()", globals(), {"cls": cls})
                except:
                    pdb.post_mortem(sys.exc_info()[2])
            elif len(cls.profiler_option):
                import cProfile

                cProfile.run("cls.prepare_process()", cls.profiler_option + "-prepare")
                cProfile.run("cls.process()", cls.profiler_option + "-process")
                cProfile.run("cls.finish()", cls.profiler_option + "-finish")
            else:
                cls.prepare_process()
                sys.call_tracing(lambda: cls.process(), [])
                cls.finish()
        else:
            cls.prepare_process()
            cls.process()
            cls.finish()
Ejemplo n.º 16
0
def reference_viewer(sys_argv):

    # default of 1000 is a little too small
    sys.setrecursionlimit(2000)
        
    viewer = ReferenceViewer(layout=default_layout)
    viewer.add_default_plugins()

    # Parse command line options with optparse module
    from optparse import OptionParser

    usage = "usage: %prog [options] cmd [args]"
    optprs = OptionParser(usage=usage,
                          version=('%%prog %s' % version.version))
    viewer.add_default_options(optprs)

    (options, args) = optprs.parse_args(sys_argv[1:])

    if options.display:
        os.environ['DISPLAY'] = options.display

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('viewer.main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys_argv[0]))
        profile.run('viewer.main(options, args)')

    else:
        viewer.main(options, args)
Ejemplo n.º 17
0
from runtime import Runtime
import sys
import pdb

runt = Runtime()
# receive filename from a user
pdb.run("runt.top(sys.argv[1])")

Ejemplo n.º 18
0
def main(*args):
    import m5

    import core
    import debug
    import defines
    import event
    import info
    import stats
    import trace

    from util import fatal

    if len(args) == 0:
        options, arguments = parse_options()
    elif len(args) == 2:
        options, arguments = args
    else:
        raise TypeError, "main() takes 0 or 2 arguments (%d given)" % len(args)

    m5.options = options

    def check_tracing():
        if defines.TRACING_ON:
            return

        fatal("Tracing is not enabled.  Compile with TRACING_ON")

    if not os.path.isdir(options.outdir):
        os.makedirs(options.outdir)

    # These filenames are used only if the redirect_std* options are set
    stdout_file = os.path.join(options.outdir, options.stdout_file)
    stderr_file = os.path.join(options.outdir, options.stderr_file)

    # Print redirection notices here before doing any redirection
    if options.redirect_stdout and not options.redirect_stderr:
        print "Redirecting stdout and stderr to", stdout_file
    else:
        if options.redirect_stdout:
            print "Redirecting stdout to", stdout_file
        if options.redirect_stderr:
            print "Redirecting stderr to", stderr_file

    # Now redirect stdout/stderr as desired
    if options.redirect_stdout:
        redir_fd = os.open(stdout_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stdout.fileno())
        if not options.redirect_stderr:
            os.dup2(redir_fd, sys.stderr.fileno())

    if options.redirect_stderr:
        redir_fd = os.open(stderr_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stderr.fileno())

    done = False

    if options.build_info:
        done = True
        print 'Build information:'
        print
        print 'compiled %s' % defines.compileDate;
        print 'build options:'
        keys = defines.buildEnv.keys()
        keys.sort()
        for key in keys:
            val = defines.buildEnv[key]
            print '    %s = %s' % (key, val)
        print

    if options.copyright:
        done = True
        print info.COPYING
        print

    if options.readme:
        done = True
        print 'Readme:'
        print
        print info.README
        print

    if options.debug_help:
        done = True
        check_tracing()
        debug.help()

    if options.list_sim_objects:
        import SimObject
        done = True
        print "SimObjects:"
        objects = SimObject.allClasses.keys()
        objects.sort()
        for name in objects:
            obj = SimObject.allClasses[name]
            print "    %s" % obj
            params = obj._params.keys()
            params.sort()
            for pname in params:
                param = obj._params[pname]
                default = getattr(param, 'default', '')
                print "        %s" % pname
                if default:
                    print "            default: %s" % default
                print "            desc: %s" % param.desc
                print
            print

    if done:
        sys.exit(0)

    # setting verbose and quiet at the same time doesn't make sense
    if options.verbose > 0 and options.quiet > 0:
        options.usage(2)

    verbose = options.verbose - options.quiet
    if options.verbose >= 0:
        print "gem5 Simulator System.  http://gem5.org"
        print brief_copyright
        print

        print "gem5 compiled %s" % defines.compileDate;

        print "gem5 started %s" % \
            datetime.datetime.now().strftime("%b %e %Y %X")
        print "gem5 executing on %s" % socket.gethostname()

        print "command line:",
        for argv in sys.argv:
            print argv,
        print

    # check to make sure we can find the listed script
    if not arguments or not os.path.isfile(arguments[0]):
        if arguments and not os.path.isfile(arguments[0]):
            print "Script %s not found" % arguments[0]

        options.usage(2)

    # tell C++ about output directory
    core.setOutputDir(options.outdir)

    # update the system path with elements from the -p option
    sys.path[0:0] = options.path

    # set stats options
    stats.initText(options.stats_file)

    # set debugging options
    debug.setRemoteGDBPort(options.remote_gdb_port)
    for when in options.debug_break:
        debug.schedBreakCycle(int(when))

    if options.debug_flags:
        check_tracing()

        on_flags = []
        off_flags = []
        for flag in options.debug_flags:
            off = False
            if flag.startswith('-'):
                flag = flag[1:]
                off = True

            if flag not in debug.flags:
                print >>sys.stderr, "invalid debug flag '%s'" % flag
                sys.exit(1)

            if off:
                debug.flags[flag].disable()
            else:
                debug.flags[flag].enable()

    if options.trace_start:
        check_tracing()
        e = event.create(trace.enable, event.Event.Trace_Enable_Pri)
        event.mainq.schedule(e, options.trace_start)
    else:
        trace.enable()

    trace.output(options.trace_file)

    for ignore in options.trace_ignore:
        check_tracing()
        trace.ignore(ignore)

    sys.argv = arguments
    sys.path = [ os.path.dirname(sys.argv[0]) ] + sys.path

    filename = sys.argv[0]
    filedata = file(filename, 'r').read()
    filecode = compile(filedata, filename, 'exec')
    scope = { '__file__' : filename,
              '__name__' : '__m5_main__' }

    # we want readline if we're doing anything interactive
    if options.interactive or options.pdb:
        exec "import readline" in scope

    # if pdb was requested, execfile the thing under pdb, otherwise,
    # just do the execfile normally
    if options.pdb:
        import pdb
        import traceback

        pdb = pdb.Pdb()
        try:
            pdb.run(filecode, scope)
        except SystemExit:
            print "The program exited via sys.exit(). Exit status: ",
            print sys.exc_info()[1]
        except:
            traceback.print_exc()
            print "Uncaught exception. Entering post mortem debugging"
            t = sys.exc_info()[2]
            while t.tb_next is not None:
                t = t.tb_next
                pdb.interaction(t.tb_frame,t)
    else:
        exec filecode in scope

    # once the script is done
    if options.interactive:
        interact(scope)
Ejemplo n.º 19
0
    if sys.hexversion < 0x2070000:
        print("ec2rl requires Python 2.7+, but running version is {0}.".format(
            platform.python_version()))
        return 201

    import ec2rlcore.main
    ec2rl = ec2rlcore.main.Main()
    return ec2rl()


def pdb_signal_handler(signal_num, stack_frame):
    """
    Handles the SIGUSR1 signal to initiate pdb
    """
    print("Received signal: {}".format(signal_num))
    pdb.Pdb().set_trace(stack_frame)


if __name__ == "__main__":
    if "--pdb" in sys.argv:
        sys.argv.remove("--pdb")
        sys.exit(pdb.run("main()"))
    else:
        # SIGUSR1 is POSIX signal 10
        signal.signal(signal.SIGUSR1, pdb_signal_handler)
        if main():
            sys.exit(0)
        else:
            sys.exit(1)
Ejemplo n.º 20
0
		'   \t   \t   \telse: F = string.split(L)' \
		]
	epilogue = [ \
		'   \t   \tif not PFLAG: continue', \
		'   \t   \tif aflag:', \
		'   \t   \t   \tif FS: print string.joinfields(F, FS)', \
		'   \t   \t   \telse: print string.join(F)', \
		'   \t   \telse: print L', \
		]
else:
	prologue = ['if 1:']
	epilogue = []

# Note that we indent using tabs only, so that any indentation style
# used in 'command' will come out right after re-indentation.

program = string.joinfields(prologue, '\n') + '\n'
for line in SCRIPT:
	program = program + ('   \t   \t' + line + '\n')
program = program + (string.joinfields(epilogue, '\n') + '\n')

import tempfile
fp = tempfile.NamedTemporaryFile()
fp.write(program)
fp.flush()
if DFLAG:
	import pdb
	pdb.run('execfile(' + `tfn` + ')')
else:
	execfile(tfn)
Ejemplo n.º 21
0
def pdebug():
    import pdb
    pdb.run('debug()')
Ejemplo n.º 22
0
import pdb

def test_debugger(some_int):
    print 'start some_int>>>', some_int
    return_int = 10 / some_int
    print 'end some_int>>', some_int
    return return_int

if __name__ == '__main__':
    pdb.run('test_debugger(0)')
Ejemplo n.º 23
0
        logger_setup(args.output_dir, 'gtdbtk_toolset.log',
                     'GTDB Tk converter', version(), args.silent)
    except:
        logger_setup(None, 'gtdbtk_toolset.log', 'GTDB Tk converter',
                     __version__, args.silent)

    # do what we came here to do
    try:
        parser = OptionsParser()
        if False:
            # import pstats
            # p = pstats.Stats('prof')
            # p.sort_stats('cumulative').print_stats(10)
            # p.sort_stats('time').print_stats(10)
            import cProfile

            cProfile.run('parser.parse_options(args)', 'prof')
        elif False:
            import pdb

            pdb.run(parser.parse_options(args))
        else:
            parser.parse_options(args)
    except SystemExit:
        print(
            "\n  Controlled exit resulting from an unrecoverable error or warning."
        )
    except:
        print("\nUnexpected error:", sys.exc_info()[0])
        raise
Ejemplo n.º 24
0
        "/nfs/ug/homes-1/b/brkicisi/Documents/2019_summer/AddILA/.d_getCells_2.txt",
        'w') as f:
    for cn in allCells:
        f.write(cn + "\n")

import os
import subprocess
from com.xilinx.rapidwright.debug import ProbeRouter
from com.xilinx.rapidwright.design import Design
from com.xilinx.rapidwright.util import FileTools
from java.util import Collections
from java.util import HashMap
from pprint import pprint

design = Design.readCheckpoint(
    "/nfs/ug/homes-1/b/brkicisi/Documents/2019_summer/ILA/tutorial_2/add_ila_out.dcp"
)
d = design
netlist = design.getNetlist()
ProbeRouter.findILAs(design)
netlist.getCellInstFromHierName("top/u_ila_0").getCellPorts()
net = netlist.getCellInstFromHierName("top/u_ila_0").getPortInst(
    "probe0[0]").getNet()
probesMap = HashMap()
probesMap.put("top/u_ila_0/probe0[0]", "tut_2_dsgn_i/gpio_led/gpio_io_o[0]")

#ProbeRouter.updateProbeConnections(design,probesMap)
import pdb

pdb.run('ProbeRouter.updateProbeConnections(design,probesMap)')
Ejemplo n.º 25
0
def t():
    import pdb
    pdb.run('main()')
Ejemplo n.º 26
0
##### main
def main(args=[]):
    # create buffer
    buffer = gtksourceview.Buffer()
    mgr = gtksourceview.style_scheme_manager_get_default()
    style_scheme = mgr.get_scheme('classic')
    if style_scheme:
        buffer.set_style_scheme(style_scheme)

    # parse arguments
    if len(args) > 2:
        open_file(buffer, args[1])
    else:
        open_file(buffer, args[0])

    # create first window
    window = create_main_window(buffer)
    window.set_default_size(500, 500)
    window.show()

    # main loop
    gtk.main()


if __name__ == '__main__':
    if '--debug' in sys.argv:
        import pdb
        pdb.run('main(sys.argv)')
    else:
        main(sys.argv)
Ejemplo n.º 27
0
    if firstdelete:
        try:
            os.remove(abspath(filename))
        except OSError:
            pass

    for proc_i in range(subprocs):
        if not os.fork():
            # we are in a subprocess
            for_subprocess(proc_i, subthreads, logrecords, locktests, filename)
            break
    else:
        # we are in the parent process
        for i in range(subprocs):
            os.wait()  # wait for subprocesses

        # finally, check the resulting log file content
        if firstdelete:
            print(check_records_and_len(filename, expected_len))
        else:
            print(check_records_only(filename))

    print(f'end.')


# try running the script simultaneously using different Python versions :)
if __name__ == '__main__':
    import pdb
    pdb.run(main(*sys.argv[1:]))
Ejemplo n.º 28
0
bot = ircbot.IRCBot(settings.Settings())
bot.add_timer(datetime.timedelta(0, 600), True, bot.send_all_networks, "PING :iamabanana")

# Add paths for debugger
sys.path += [os.path.join(sys.path[0], "ircclient"), os.path.join(sys.path[0], "plugins")]

def Tick():
	while True:
		try:
			if bot.need_reload.has_key('main') and bot.need_reload['main']:
				reload(ircbot)
				reload(settings)
				print "Collected %s objects out of %s. Garbarge are %s objects." % (gc.collect(2), 
					len(gc.get_objects()), len(gc.garbage))
				bot.need_reload['main'] = False
				bot.on_reload()

			bot.tick()

			time.sleep(0.1)
		except KeyboardInterrupt:
			print ""
			print "Entering debug mode, use c(ontinue) to exit. Don't stay here to long."
			print "This is " + bot.settings.networks.values()[0]["nick"]
			pdb.set_trace()
		except:
			raise

# Run bot with debugger
pdb.run(Tick())
Ejemplo n.º 29
0
# coding: utf-8
# pdb #

command = {'break/b 行号/函数名': '设置断点', 'continue/c': '继续执行程序', 'list/l': '查看当前的代码段', 'step/s': '进入函数',
           'return/r': '执行代码直到从当前函数返回', 'exit': '终止并退出', 'q': '终止并重启', 'next/n': '执行下一行', 'pp 变量名': '打印变量的值',
           'help': '帮助', 'args/a': '打印当前函数的参数', 'jump/j': '让程序跳到指定行'}

# 开启pdb调式的方法
# 1. 命令行
# python -m pdb test.py   ## 断点就是程序执行的第一行

# 2. python中调试
import pdb

pdb.run('modulename.test()')

# 3. 插入断点
import pdb

pdb.set_trace()

# example ############
# 1
import pdb

a = "aaa"
pdb.set_trace()  # 脚本直接运行会停止在下一行
b = "bbb"
c = "ccc"
final = a + b + c
print(final)
Ejemplo n.º 30
0
def main(*args):
    import m5

    import core
    import debug
    import defines
    import event
    import info
    import stats
    import trace

    from util import inform, fatal, panic, isInteractive

    if len(args) == 0:
        options, arguments = parse_options()
    elif len(args) == 2:
        options, arguments = args
    else:
        raise TypeError("main() takes 0 or 2 arguments (%d given)" % len(args))

    m5.options = options

    # Set the main event queue for the main thread.
    event.mainq = event.getEventQueue(0)
    event.setEventQueue(event.mainq)

    if not os.path.isdir(options.outdir):
        os.makedirs(options.outdir)

    # These filenames are used only if the redirect_std* options are set
    stdout_file = os.path.join(options.outdir, options.stdout_file)
    stderr_file = os.path.join(options.outdir, options.stderr_file)

    # Print redirection notices here before doing any redirection
    if options.redirect_stdout and not options.redirect_stderr:
        print("Redirecting stdout and stderr to", stdout_file)
    else:
        if options.redirect_stdout:
            print("Redirecting stdout to", stdout_file)
        if options.redirect_stderr:
            print("Redirecting stderr to", stderr_file)

    # Now redirect stdout/stderr as desired
    if options.redirect_stdout:
        redir_fd = os.open(stdout_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stdout.fileno())
        if not options.redirect_stderr:
            os.dup2(redir_fd, sys.stderr.fileno())

    if options.redirect_stderr:
        redir_fd = os.open(stderr_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stderr.fileno())

    done = False

    if options.build_info:
        done = True
        print('Build information:')
        print()
        print('compiled %s' % defines.compileDate)
        print('build options:')
        keys = list(defines.buildEnv.keys())
        keys.sort()
        for key in keys:
            val = defines.buildEnv[key]
            print('    %s = %s' % (key, val))
        print()

    if options.copyright:
        done = True
        print(info.COPYING)
        print()

    if options.readme:
        done = True
        print('Readme:')
        print()
        print(info.README)
        print()

    if options.debug_help:
        done = True
        _check_tracing()
        debug.help()

    if options.list_sim_objects:
        import SimObject
        done = True
        print("SimObjects:")
        objects = list(SimObject.allClasses.keys())
        objects.sort()
        for name in objects:
            obj = SimObject.allClasses[name]
            print("    %s" % obj)
            params = list(obj._params.keys())
            params.sort()
            for pname in params:
                param = obj._params[pname]
                default = getattr(param, 'default', '')
                print("        %s" % pname)
                if default:
                    print("            default: %s" % default)
                print("            desc: %s" % param.desc)
                print()
            print()

    if done:
        sys.exit(0)

    # setting verbose and quiet at the same time doesn't make sense
    if options.verbose > 0 and options.quiet > 0:
        options.usage(2)

    verbose = options.verbose - options.quiet
    if verbose >= 0:
        print("gem5 Simulator System.  http://gem5.org")
        print(brief_copyright)
        print()

        print("gem5 compiled %s" % defines.compileDate)

        print("gem5 started %s" %
              datetime.datetime.now().strftime("%b %e %Y %X"))
        print("gem5 executing on %s, pid %d" %
              (socket.gethostname(), os.getpid()))

        # in Python 3 pipes.quote() is moved to shlex.quote()
        import pipes
        print("command line:", " ".join(map(pipes.quote, sys.argv)))
        print()

    # check to make sure we can find the listed script
    if not arguments or not os.path.isfile(arguments[0]):
        if arguments and not os.path.isfile(arguments[0]):
            print("Script %s not found" % arguments[0])

        options.usage(2)

    # tell C++ about output directory
    core.setOutputDir(options.outdir)

    # update the system path with elements from the -p option
    sys.path[0:0] = options.path

    # set stats options
    stats.addStatVisitor(options.stats_file)

    # Disable listeners unless running interactively or explicitly
    # enabled
    if options.listener_mode == "off":
        m5.disableAllListeners()
    elif options.listener_mode == "auto":
        if not isInteractive():
            inform("Standard input is not a terminal, disabling listeners.")
            m5.disableAllListeners()
    elif options.listener_mode == "on":
        pass
    else:
        panic("Unhandled listener mode: %s" % options.listener_mode)

    if options.listener_loopback_only:
        m5.listenersLoopbackOnly()

    # set debugging options
    debug.setRemoteGDBPort(options.remote_gdb_port)
    for when in options.debug_break:
        debug.schedBreak(int(when))

    if options.debug_flags:
        _check_tracing()

        on_flags = []
        off_flags = []
        for flag in options.debug_flags:
            off = False
            if flag.startswith('-'):
                flag = flag[1:]
                off = True

            if flag not in debug.flags:
                print("invalid debug flag '%s'" % flag, file=sys.stderr)
                sys.exit(1)

            if off:
                debug.flags[flag].disable()
            else:
                debug.flags[flag].enable()

    if options.debug_start:
        _check_tracing()
        e = event.create(trace.enable, event.Event.Debug_Enable_Pri)
        event.mainq.schedule(e, options.debug_start)
    else:
        trace.enable()

    if options.debug_end:
        _check_tracing()
        e = event.create(trace.disable, event.Event.Debug_Enable_Pri)
        event.mainq.schedule(e, options.debug_end)

    trace.output(options.debug_file)

    for ignore in options.debug_ignore:
        _check_tracing()
        trace.ignore(ignore)

    sys.argv = arguments
    sys.path = [os.path.dirname(sys.argv[0])] + sys.path

    filename = sys.argv[0]
    filedata = open(filename, 'r').read()
    filecode = compile(filedata, filename, 'exec')
    scope = {'__file__': filename, '__name__': '__m5_main__'}

    # if pdb was requested, execfile the thing under pdb, otherwise,
    # just do the execfile normally
    if options.pdb:
        import pdb
        import traceback

        pdb = pdb.Pdb()
        try:
            pdb.run(filecode, scope)
        except SystemExit:
            print("The program exited via sys.exit(). Exit status: ", end=' ')
            print(sys.exc_info()[1])
        except:
            traceback.print_exc()
            print("Uncaught exception. Entering post mortem debugging")
            t = sys.exc_info()[2]
            while t.tb_next is not None:
                t = t.tb_next
                pdb.interaction(t.tb_frame, t)
    else:
        exec(filecode, scope)

    # once the script is done
    if options.interactive:
        interact(scope)
Ejemplo n.º 31
0

def interact(banner=None, readfunc=None, local=None):
    """Closely emulate the interactive Python interpreter.

    This is a backwards compatible interface to the InteractiveConsole
    class.  When readfunc is not specified, it attempts to import the
    readline module to enable GNU readline if it is available.

    Arguments (all optional, all default to None):

    banner -- passed to InteractiveConsole.interact()
    readfunc -- if not None, replaces InteractiveConsole.raw_input()
    local -- passed to InteractiveInterpreter.__init__()

    """
    console = InteractiveConsole(local)
    if readfunc is not None:
        console.raw_input = readfunc
    else:
        try:
            import readline
        except ImportError:
            pass
    console.interact(banner)


if __name__ == '__main__':
    import pdb
    pdb.run("interact()\n")
Ejemplo n.º 32
0
                      help="Run the server instead of client")
    optprs.add_option("--set", dest="set", default=False,
                      action="store_true",
                      help="Run the set_fno client")
    optprs.add_option("--svcname", dest="svcname", metavar="NAME",
                      default=serviceName,
                      help="Register using NAME as service name")
    ssdlog.addlogopts(optprs)

    (options, args) = optprs.parse_args(sys.argv[1:])

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('server(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print "%s profile:" % sys.argv[0]
        profile.run('server(options, args)')

    elif options.server:
        server(options, args)

    elif options.set:
        client_set(options, args)

    else:
r--------> return快速执行到函数最后一行

"""

#有些情况直接按  c  不行,先按 n 再执行其它操作



######################## #第二种方式
#用pdb模块交互式调试
import pdb

def test():
    print("")

pdb.run(test())


######################第三程序中埋点
import pdb
def printest(a,b):

    print(a,b)
    return a+b

a=100
b=200

pdb.set_trace()    #当程序执行到这个步会自动进入调试模式

ret=printest(a,b)
Ejemplo n.º 34
0
def main(*args):
    import m5

    import core
    import debug
    import defines
    import event
    import info
    import stats
    import trace

    from util import fatal

    if len(args) == 0:
        options, arguments = parse_options()
    elif len(args) == 2:
        options, arguments = args
    else:
        raise TypeError, "main() takes 0 or 2 arguments (%d given)" % len(args)

    m5.options = options

    def check_tracing():
        if defines.TRACING_ON:
            return

        fatal("Tracing is not enabled.  Compile with TRACING_ON")

    # Set the main event queue for the main thread.
    event.mainq = event.getEventQueue(0)
    event.setEventQueue(event.mainq)

    if not os.path.isdir(options.outdir):
        os.makedirs(options.outdir)

    # These filenames are used only if the redirect_std* options are set
    stdout_file = os.path.join(options.outdir, options.stdout_file)
    stderr_file = os.path.join(options.outdir, options.stderr_file)

    # Print redirection notices here before doing any redirection
    if options.redirect_stdout and not options.redirect_stderr:
        print "Redirecting stdout and stderr to", stdout_file
    else:
        if options.redirect_stdout:
            print "Redirecting stdout to", stdout_file
        if options.redirect_stderr:
            print "Redirecting stderr to", stderr_file

    # Now redirect stdout/stderr as desired
    if options.redirect_stdout:
        redir_fd = os.open(stdout_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stdout.fileno())
        if not options.redirect_stderr:
            os.dup2(redir_fd, sys.stderr.fileno())

    if options.redirect_stderr:
        redir_fd = os.open(stderr_file, os.O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stderr.fileno())

    done = False

    if options.build_info:
        done = True
        print 'Build information:'
        print
        print 'compiled %s' % defines.compileDate
        print 'build options:'
        keys = defines.buildEnv.keys()
        keys.sort()
        for key in keys:
            val = defines.buildEnv[key]
            print '    %s = %s' % (key, val)
        print

    if options.copyright:
        done = True
        print info.COPYING
        print

    if options.readme:
        done = True
        print 'Readme:'
        print
        print info.README
        print

    if options.debug_help:
        done = True
        check_tracing()
        debug.help()

    if options.list_sim_objects:
        import SimObject
        done = True
        print "SimObjects:"
        objects = SimObject.allClasses.keys()
        objects.sort()
        for name in objects:
            obj = SimObject.allClasses[name]
            print "    %s" % obj
            params = obj._params.keys()
            params.sort()
            for pname in params:
                param = obj._params[pname]
                default = getattr(param, 'default', '')
                print "        %s" % pname
                if default:
                    print "            default: %s" % default
                print "            desc: %s" % param.desc
                print
            print

    if done:
        sys.exit(0)

    # setting verbose and quiet at the same time doesn't make sense
    if options.verbose > 0 and options.quiet > 0:
        options.usage(2)

    verbose = options.verbose - options.quiet
    if verbose >= 0:
        print "gem5 Simulator System.  http://gem5.org"
        print brief_copyright
        print

        print "gem5 compiled %s" % defines.compileDate

        print "gem5 started %s" % \
            datetime.datetime.now().strftime("%b %e %Y %X")
        print "gem5 executing on %s" % socket.gethostname()

        # ADARSH
        print "gem5 process id %s" % os.getpid()
        # in Python 3 pipes.quote() is moved to shlex.quote()
        import pipes
        print "command line:", " ".join(map(pipes.quote, sys.argv))
        print

    # check to make sure we can find the listed script
    if not arguments or not os.path.isfile(arguments[0]):
        if arguments and not os.path.isfile(arguments[0]):
            print "Script %s not found" % arguments[0]

        options.usage(2)

    # tell C++ about output directory
    core.setOutputDir(options.outdir)

    # update the system path with elements from the -p option
    sys.path[0:0] = options.path

    # set stats options
    stats.initText(options.stats_file)

    # set debugging options
    debug.setRemoteGDBPort(options.remote_gdb_port)
    for when in options.debug_break:
        debug.schedBreak(int(when))

    if options.debug_flags:
        check_tracing()

        on_flags = []
        off_flags = []
        for flag in options.debug_flags:
            off = False
            if flag.startswith('-'):
                flag = flag[1:]
                off = True

            if flag not in debug.flags:
                print >> sys.stderr, "invalid debug flag '%s'" % flag
                sys.exit(1)

            if off:
                debug.flags[flag].disable()
            else:
                debug.flags[flag].enable()

    if options.debug_start:
        check_tracing()
        e = event.create(trace.enable, event.Event.Debug_Enable_Pri)
        event.mainq.schedule(e, options.debug_start)
    else:
        trace.enable()

    trace.output(options.debug_file)

    for ignore in options.debug_ignore:
        check_tracing()
        trace.ignore(ignore)

    sys.argv = arguments
    sys.path = [os.path.dirname(sys.argv[0])] + sys.path

    filename = sys.argv[0]
    filedata = file(filename, 'r').read()
    filecode = compile(filedata, filename, 'exec')
    scope = {'__file__': filename, '__name__': '__m5_main__'}

    # we want readline if we're doing anything interactive
    if options.interactive or options.pdb:
        exec "import readline" in scope

    # if pdb was requested, execfile the thing under pdb, otherwise,
    # just do the execfile normally
    if options.pdb:
        import pdb
        import traceback

        pdb = pdb.Pdb()
        try:
            pdb.run(filecode, scope)
        except SystemExit:
            print "The program exited via sys.exit(). Exit status: ",
            print sys.exc_info()[1]
        except:
            traceback.print_exc()
            print "Uncaught exception. Entering post mortem debugging"
            t = sys.exc_info()[2]
            while t.tb_next is not None:
                t = t.tb_next
                pdb.interaction(t.tb_frame, t)
    else:
        exec filecode in scope

    # once the script is done
    if options.interactive:
        interact(scope)
Ejemplo n.º 35
0
        commonPy2.configMT.verbose = True
        sys.argv.remove("-verbose")

    # No other options must remain in the cmd line...
    if astFile is None or len(sys.argv) < 2:
        panic('Usage: %s [-verbose] [-useOSS] [-o dirname] input1.aadl [input2.aadl] ...\n' % sys.argv[0])  # pragma: no cover
    commonPy2.configMT.showCode = True
    for f in sys.argv[1:]:
        if not os.path.isfile(f):
            panic("'%s' is not a file!\n" % f)  # pragma: no cover

    ParseAADLfilesAndResolveSignals()
    serialize_package = {
        'g_signals': commonPy2.aadlAST.g_signals,
        'g_apLevelContainers': commonPy2.aadlAST.g_apLevelContainers,
        'g_subProgramImplementations': commonPy2.aadlAST.g_subProgramImplementations,
        'g_processImplementations': commonPy2.aadlAST.g_processImplementations,
        'g_threadImplementations': commonPy2.aadlAST.g_threadImplementations,
        'g_systems': commonPy2.aadlAST.g_systems
    }
    import cPickle
    cPickle.dump(serialize_package, open(astFile, 'w'))

if __name__ == "__main__":
    if "-pdb" in sys.argv:
        sys.argv.remove("-pdb")  # pragma: no cover
        import pdb  # pragma: no cover
        pdb.run('main()')  # pragma: no cover
    else:
        main()
Ejemplo n.º 36
0
#!/usr/bin/env python3

import pdb
import plot_energy

pdb.run('plot_energy.main()')

Ejemplo n.º 37
0
    ##                   default='monitor',
    ##                   help="Synchronize from monitor named NAME")
    ## optprs.add_option("--monchannels", dest="monchannels",
    ##                   default='status', metavar="NAMES",
    ##                   help="Specify monitor channels to subscribe to")
    ## optprs.add_option("--monport", dest="monport", type="int",
    ##                   help="Register monitor using PORT", metavar="PORT")

    (options, args) = optprs.parse_args(sys.argv[1:])

    if options.display:
        os.environ['DISPLAY'] = options.display

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('viewer.main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys.argv[0]))
        profile.run('viewer.main(options, args)')

    else:
        viewer.main(options, args)

# END
Ejemplo n.º 38
0
    reg.loadElementTree(tree)
    endTimer(args.time, '* Time to parse ElementTree =')

    if (args.validate):
        reg.validateGroups()

    if (args.dump):
        write('* Dumping registry to regdump.txt', file=sys.stderr)
        reg.dumpReg(filehandle=open('regdump.txt', 'w', encoding='utf-8'))

    # create error/warning & diagnostic files
    if (args.errfile):
        errWarn = open(args.errfile, 'w', encoding='utf-8')
    else:
        errWarn = sys.stderr

    if (args.diagfile):
        diag = open(args.diagfile, 'w', encoding='utf-8')
    else:
        diag = None

    if (args.debug):
        pdb.run('genTarget(args)')
    elif (args.profile):
        import cProfile, pstats
        cProfile.run('genTarget(args)', 'profile.txt')
        p = pstats.Stats('profile.txt')
        p.strip_dirs().sort_stats('time').print_stats(50)
    else:
        genTarget(args)
import pdb


def for_jump(count):
    print("entered in to the function")
    lis = [1, 2, 3, 4, 5, 6]
    print("reaching to the for loop")
    for var in lis:
        print("enter in to the loop")
        count += 1
        print(var)
        print(count)


pdb.run("for_jump(2)")

# from forloop to outside but cannot jump from outside into a loop
#from outside to finally but cannot jump from finnaly to outside
#l - will show the current exceuting breakpoint
# !pdb.run("for_jump(9)") - can change the value while debugging but the cursor will not change
Ejemplo n.º 40
0
    # Loop over targets, building each
    generated = 0
    for genOpts in buildList:
        if (genOpts == None):
            break
        if (target and target != genOpts.filename):
            # write('*** Skipping', genOpts.filename)
            continue
        write('*** Building', genOpts.filename)
        generated = generated + 1
        startTimer()
        gen = COutputGenerator(errFile=errWarn,
                               warnFile=errWarn,
                               diagFile=diag)
        reg.setGenerator(gen)
        reg.apiGen(genOpts)
        write('** Generated', genOpts.filename)
        endTimer('Time to generate ' + genOpts.filename + ' =')
    if (target and generated == 0):
        write('Failed to generate target:', target)

if (debug):
    pdb.run('genHeaders()')
elif (profile):
    import cProfile, pstats
    cProfile.run('genHeaders()', 'profile.txt')
    p = pstats.Stats('profile.txt')
    p.strip_dirs().sort_stats('time').print_stats(50)
else:
    genHeaders()
Ejemplo n.º 41
0
        middle = int(math.floor((p + r) / 2.))
        merge_sort(A, p, middle)
        merge_sort(A, middle + 1, r)
        merge(A, p, middle, r)

def sort(l):
    # copying
    sorted_list = list(l)
    merge_sort(sorted_list, 0, len(l) - 1)
    return sorted_list

class TestSorted(unittest.TestCase):

    def setUp(self):
        self.lists = (
                [1,],
                [2, 3],
                [4, 3, 2, 2, 6, 7],
                [0, 1, 2, 3, 4, 5, 6, 7, 7, 8, 9, 10],
                [12, 34, 32, 34, 32, 34, 65, 34, 1, 4, 3, 5],
                [3, 5, 6, 3, 5, 6, 7, 3, 5, 6, 3, 5, 3, 123])

    def test_sorted(self):
        for original_list in self.lists:
            sorted_list = sort(original_list)
            self.assertListEqual(sorted_list, sorted(original_list))

if __name__ == '__main__':
    pdb.run('sort([4, 3, 2, 2, 6, 7])')
    unittest.main()
Ejemplo n.º 42
0
#T# pdb is the builtin Python debugger, it has breakpoints, stepping through the code, printing the values of variables, post-mortem debugging, debugging of modules, functions, scripts, among other features

#T# pdb can be executed with an script argument to debug said script, the following syntax is done in the operating system shell
# SYNTAX python3 -m pdb script1.py
#T# python3 is the Python executable, -m pdb script1.py runs pdb to debug script1.py (see the file titled Interpreter), this automatically enters post-mortem if script1 crashes

#T# the pdb module is imported to use the pdb debugger as part of a script
import pdb

#T# the run function of the pdb module allows debugging the execution of a Python string

# SYNTAX pdb.run('string1')
#T# the pdb debugger is started right before the execution of string1, and is used to debug whatever string1 executes

pdb.run(
    'import S01_Basic_syntax'
)  # this debugs the S01_Basic_syntax.py file, because the import statement executes the imported module

#T# the following code is used to show the syntax of the pdb debugger in its interactive mode
output_var1 = "help variable to show the different output of the pdb debugger"
var1 = [5, 2, 3]
var2 = 7


def func1(num1, num2):
    num3 = num1 + num2
    print("func1_string1")
    return num3


def func2():
    # Loop over targets, building each
    generated = 0
    for genOpts in buildList:
        if (genOpts == None):
            break
        if (target and target != genOpts.filename):
            # write('*** Skipping', genOpts.filename)
            continue
        write('*** Building', genOpts.filename)
        generated = generated + 1
        startTimer()
        gen = COutputGenerator(errFile=errWarn,
                               warnFile=errWarn,
                               diagFile=diag)
        reg.setGenerator(gen)
        reg.apiGen(genOpts)
        write('** Generated', genOpts.filename)
        endTimer('Time to generate ' + genOpts.filename + ' =')
    if (target and generated == 0):
        write('Failed to generate target:', target)

if (debug):
    pdb.run('genHeaders()')
elif (profile):
    import cProfile, pstats
    cProfile.run('genHeaders()', 'profile.txt')
    p = pstats.Stats('profile.txt')
    p.strip_dirs().sort_stats('time').print_stats(50)
else:
    genHeaders()
Ejemplo n.º 44
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 10 11:43:25 2019
@author: fred
"""
import pdb
pdb.run("a=3")

import sys
sys.path.insert(0, '/home/fred/Desktop/GPyOpt/')
import GPyOpt
from qutip import sigmax, sigmaz, sigmay, mesolve, Qobj, Options, fidelity
import numpy as np
from numpy import random
import matplotlib.pylab as plt
from scipy.special import erfinv

## TODO
## a. Add BlochSphere capa
## c. wrap f to take only one argument first DONE
## d. create bo_args DONE
## e. debug DONE
## f. implement logic if nothing has changed just return last results (NOT NOW)
## g. find old simulations with target
## h. find a state target DONE
## i. test EI acquisition_function
## j. Incorporate to batch_few_shots
## k. Profiling (Add more timers)
## l. Optim
## m. bch: average
Ejemplo n.º 45
0
Archivo: pdbfib.py Proyecto: rosedu/rtt
#!/usr/bin/env python

import pdb

def main():
    low, high = 0, 1
    for i in xrange(10):
        print high
        low, high = high, low + high
 
if __name__ == '__main__':
    pdb.run('main()')
Ejemplo n.º 46
0
import pdb
from .interface import main

pdb.set_trace()
pdb.run('main()')
Ejemplo n.º 47
0
        "--port", dest="port", metavar="NUM", type="int", default=23099, help="Port to use for receiving data"
    )
    optprs.add_option("--other", dest="other", metavar="HOST", help="Host to communicate with")
    optprs.add_option(
        "--stderr", dest="logstderr", default=False, action="store_true", help="Copy logging also to stderr"
    )
    optprs.add_option(
        "--profile", dest="profile", action="store_true", default=False, help="Run the profiler on main()"
    )

    (options, args) = optprs.parse_args(sys.argv[1:])

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run("main(options, args)")

    # Are we profiling this?
    elif options.profile:
        import profile

        print ("%s profile:" % sys.argv[0])
        profile.run("main(options, args)")

    else:
        main(options, args)


# END
Ejemplo n.º 48
0
    # options. The options are set before XML loading as they may affect it.
    reg = Registry(gen, options)

    # Parse the specified registry XML into an ElementTree object
    startTimer(args.time)
    tree = etree.parse(args.registry)
    endTimer(args.time, '* Time to make ElementTree =')

    # Load the XML tree into the registry object
    startTimer(args.time)
    reg.loadElementTree(tree)
    endTimer(args.time, '* Time to parse ElementTree =')

    if args.validate:
        reg.validateGroups()

    if args.dump:
        logDiag('* Dumping registry to regdump.txt')
        reg.dumpReg(filehandle=open('regdump.txt', 'w', encoding='utf-8'))

    # Finally, use the output generator to create the requested target
    if args.debug:
        pdb.run('reg.apiGen()')
    else:
        startTimer(args.time)
        reg.apiGen()
        endTimer(args.time, '* Time to generate ' + options.filename + ' =')

    if not args.quiet:
        logDiag('* Generated', options.filename)
Ejemplo n.º 49
0

def interact(banner=None, readfunc=None, local=None):
    """Closely emulate the interactive Python interpreter.

    This is a backwards compatible interface to the InteractiveConsole
    class.  When readfunc is not specified, it attempts to import the
    readline module to enable GNU readline if it is available.

    Arguments (all optional, all default to None):

    banner -- passed to InteractiveConsole.interact()
    readfunc -- if not None, replaces InteractiveConsole.raw_input()
    local -- passed to InteractiveInterpreter.__init__()

    """
    console = InteractiveConsole(local)
    if readfunc is not None:
        console.raw_input = readfunc
    else:
        try:
            import readline
        except ImportError:
            pass
    console.interact(banner)


if __name__ == '__main__':
    import pdb
    pdb.run("interact()\n")
Ejemplo n.º 50
0
def pdebug():
    import pdb
    pdb.run('debug()')
Ejemplo n.º 51
0
    if os.environ.has_key('OSSIEUNITTESTSLOGCONFIG'):
        ans = raw_input("OSSIEUNITTESTSLOGCONFIG already exists as %s. Do you want to continue [Y]/N? " % os.environ[OSSIEUNITTESTSLOGCONFIG]).upper()
        if ans == "N":
            sys.exit()
    else:
        os.environ['OSSIEUNITTESTSLOGCONFIG'] = os.path.abspath(options.logconfig)

    print ""
    print "Creating the Test Domain"
    print ""
    scatest.createTestDomain()

    print ""
    print "R U N N I N G  T E S T S"
    print "SDRROOT: ", scatest.getSdrPath()
    print ""

    suite = TestCollector(files, testMethodPrefix=options.prefix, prompt=options.prompt)

    if options.xmlfile == None:
        runner = unittest.TextTestRunner(verbosity=options.verbosity)
    else:
        stream = open(options.xmlfile, "w")
        runner = xmlrunner.XMLTestRunner(stream)
    if options.debug:
        import pdb
        pdb.run("runner.run(suite)")
    else:
        runner.run(suite)
Ejemplo n.º 52
0
def test_run():
    pdb.run("test_debugger(0)")
Ejemplo n.º 53
0
            continue

        # All SCADE versions are handled by lustre_B_mapper
        # if modelingLanguage[:6] == "Lustre" or modelingLanguage[:5] == "SCADE":
        #    modelingLanguage = "Lustre"  # pragma: no cover

        # The code for these mappers needs C ASN.1 codecs
        if modelingLanguage.lower() in ["gui_ri", "gui_pi", "vhdl", "rhapsody"]:
            modelingLanguage = "C"

        if modelingLanguage in async_languages:
            m = ProcessAsync(modelingLanguage, asnFile, sp, maybeFVname, useOSS, badTypes)
            asynchronousBackends.add(m)
        else:
            ProcessSync(modelingLanguage, asnFile, sp, sp_impl, maybeFVname, useOSS, badTypes)

    # SystemsAndImplementation loop completed - time to call OnShutdown ONCE for each async backend that we loaded
    for asyncBackend in asynchronousBackends:
        asyncBackend.OnShutdown(modelingLanguage, asnFile, maybeFVname)

    ProcessCustomBackends(asnFile, useOSS, SystemsAndImplementations)


if __name__ == "__main__":
    if "-pdb" in sys.argv:
        sys.argv.remove("-pdb")  # pragma: no cover
        import pdb  # pragma: no cover pylint: disable=wrong-import-position,wrong-import-order
        pdb.run('main()')  # pragma: no cover
    else:
        main()
Ejemplo n.º 54
0
Archivo: main.py Proyecto: liangwang/m5
def main():
    import core
    import debug
    import defines
    import event
    import info
    import stats
    import trace

    def check_tracing():
        if defines.TRACING_ON:
            return

        fatal("Tracing is not enabled.  Compile with TRACING_ON")

    if not os.path.isdir(options.outdir):
        os.makedirs(options.outdir)

    # These filenames are used only if the redirect_std* options are set
    stdout_file = os.path.join(options.outdir, options.stdout_file)
    stderr_file = os.path.join(options.outdir, options.stderr_file)

    # Print redirection notices here before doing any redirection
    if options.redirect_stdout and not options.redirect_stderr:
        print "Redirecting stdout and stderr to", stdout_file
    else:
        if options.redirect_stdout:
            print "Redirecting stdout to", stdout_file
        if options.redirect_stderr:
            print "Redirecting stderr to", stderr_file

    # Now redirect stdout/stderr as desired
    if options.redirect_stdout:
        redir_fd = os.open(stdout_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stdout.fileno())
        if not options.redirect_stderr:
            os.dup2(redir_fd, sys.stderr.fileno())

    if options.redirect_stderr:
        redir_fd = os.open(stderr_file, os. O_WRONLY | os.O_CREAT | os.O_TRUNC)
        os.dup2(redir_fd, sys.stderr.fileno())

    done = False

    if options.build_info:
        done = True
        print 'Build information:'
        print
        print 'compiled %s' % defines.compileDate;
        print "revision %s" % defines.hgRev
        print 'build options:'
        keys = defines.buildEnv.keys()
        keys.sort()
        for key in keys:
            val = defines.buildEnv[key]
            print '    %s = %s' % (key, val)
        print

    if options.copyright:
        done = True
        print info.LICENSE
        print

    if options.authors:
        done = True
        print 'Author information:'
        print
        print info.AUTHORS
        print

    if options.readme:
        done = True
        print 'Readme:'
        print
        print info.README
        print

    if options.release_notes:
        done = True
        print 'Release Notes:'
        print
        print info.RELEASE_NOTES
        print

    if options.trace_help:
        done = True
        check_tracing()
        trace.help()

    if options.list_sim_objects:
        import SimObject
        done = True
        print "SimObjects:"
        objects = SimObject.allClasses.keys()
        objects.sort()
        for name in objects:
            obj = SimObject.allClasses[name]
            print "    %s" % obj
            params = obj._params.keys()
            params.sort()
            for pname in params:
                param = obj._params[pname]
                default = getattr(param, 'default', '')
                print "        %s" % pname
                if default:
                    print "            default: %s" % default
                print "            desc: %s" % param.desc
                print
            print

    if done:
        sys.exit(0)

    # setting verbose and quiet at the same time doesn't make sense
    if options.verbose > 0 and options.quiet > 0:
        options.usage(2)

    verbose = options.verbose - options.quiet
    if options.verbose >= 0:
        print "M5 Simulator System"
        print brief_copyright
        print

        print "M5 compiled %s" % defines.compileDate;
        print "M5 revision %s" % defines.hgRev

        print "M5 started %s" % datetime.datetime.now().strftime("%b %e %Y %X")
        print "M5 executing on %s" % socket.gethostname()

        print "command line:",
        for argv in sys.argv:
            print argv,
        print

    # check to make sure we can find the listed script
    if not arguments or not os.path.isfile(arguments[0]):
        if arguments and not os.path.isfile(arguments[0]):
            print "Script %s not found" % arguments[0]

        options.usage(2)

    # tell C++ about output directory
    core.setOutputDir(options.outdir)

    # update the system path with elements from the -p option
    sys.path[0:0] = options.path

    # set stats options
    stats.initText(options.stats_file)

    # set debugging options
    debug.setRemoteGDBPort(options.remote_gdb_port)
    for when in options.debug_break:
        debug.schedBreakCycle(int(when))

    if options.trace_flags:
        check_tracing()

        on_flags = []
        off_flags = []
        for flag in options.trace_flags:
            off = False
            if flag.startswith('-'):
                flag = flag[1:]
                off = True
            if flag not in trace.flags.all and flag != "All":
                print >>sys.stderr, "invalid trace flag '%s'" % flag
                sys.exit(1)

            if off:
                off_flags.append(flag)
            else:
                on_flags.append(flag)

        for flag in on_flags:
            trace.set(flag)

        for flag in off_flags:
            trace.clear(flag)

    if options.trace_start:
        check_tracing()
        e = event.create(trace.enable, event.Event.Trace_Enable_Pri)
        event.mainq.schedule(e, options.trace_start)
    else:
        trace.enable()

    trace.output(options.trace_file)

    for ignore in options.trace_ignore:
        check_tracing()
        trace.ignore(ignore)

    sys.argv = arguments
    sys.path = [ os.path.dirname(sys.argv[0]) ] + sys.path

    filename = sys.argv[0]
    filedata = file(filename, 'r').read()
    filecode = compile(filedata, filename, 'exec')
    scope = { '__file__' : filename,
              '__name__' : '__m5_main__' }

    # we want readline if we're doing anything interactive
    if options.interactive or options.pdb:
        exec "import readline" in scope

    # if pdb was requested, execfile the thing under pdb, otherwise,
    # just do the execfile normally
    if options.pdb:
        import pdb
        import traceback

        pdb = pdb.Pdb()
        try:
            pdb.run(filecode, scope)
        except SystemExit:
            print "The program exited via sys.exit(). Exit status: ",
            print sys.exc_info()[1]
        except:
            traceback.print_exc()
            print "Uncaught exception. Entering post mortem debugging"
            t = sys.exc_info()[2]
            while t.tb_next is not None:
                t = t.tb_next
                pdb.interaction(t.tb_frame,t)
    else:
        exec filecode in scope

    # once the script is done
    if options.interactive:
        interact = code.InteractiveConsole(scope)
        interact.interact("M5 Interactive Console")
Ejemplo n.º 55
0
def strpdebug():
    import pdb

    pdb.run('strptime("% Tue 3 Feb", "%% %a %d %b")')
Ejemplo n.º 56
0
    argprs = ArgumentParser()

    argprs.add_argument("--debug", dest="debug", default=False,
                        action="store_true",
                        help="Enter the pdb debugger on main()")
    argprs.add_argument("--profile", dest="profile", action="store_true",
                        default=False,
                        help="Run the profiler on main()")
    log.addlogopts(argprs)

    (options, args) = argprs.parse_known_args(sys.argv[1:])

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys.argv[0]))
        profile.run('main(options, args)')

    else:
        main(options, args)

# END
Ejemplo n.º 57
0
    optprs.add_option("--opencv", dest="opencv", default=False,
                      action="store_true",
                      help="Use OpenCv acceleration")
    optprs.add_option("--opencl", dest="opencl", default=False,
                      action="store_true",
                      help="Use OpenCL acceleration")
    optprs.add_option("--profile", dest="profile", action="store_true",
                      default=False,
                      help="Run the profiler on main()")
    log.addlogopts(optprs)

    (options, args) = optprs.parse_args(sys.argv[1:])

    # Are we debugging this?
    if options.debug:
        import pdb

        pdb.run('main(options, args)')

    # Are we profiling this?
    elif options.profile:
        import profile

        print(("%s profile:" % sys.argv[0]))
        profile.run('main(options, args)')

    else:
        main(options, args)

# END
Ejemplo n.º 58
0
        dest='configs',
        default='.',
        help=
        'Specify directory containing JSON configuration files for generators')

    args = parser.parse_args()

    # Load & parse registry
    reg = Registry()

    startTimer(args.time)
    tree = etree.parse(args.registry)
    endTimer(args.time, '* Time to make ElementTree =')

    if args.debug:
        pdb.run('reg.loadElementTree(tree)')
    else:
        startTimer(args.time)
        reg.loadElementTree(tree)
        endTimer(args.time, '* Time to parse ElementTree =')

    if (args.validate):
        reg.validateGroups()

    if (args.dump):
        write('* Dumping registry to regdump.txt', file=sys.stderr)
        reg.dumpReg(filehandle=open('regdump.txt', 'w', encoding='utf-8'))

    # create error/warning & diagnostic files
    if (args.errfile):
        errWarn = open(args.errfile, 'w', encoding='utf-8')
Ejemplo n.º 59
0
#web_server.register_handle_request_callback(handle_request)
	
bot.add_timer(datetime.timedelta(0, 600), True, bot.send_all_networks, "PING :iamabanana")
sys.path += [os.path.join(sys.path[0], "httpsrv"), os.path.join(sys.path[0], "ircclient"),
	     os.path.join(sys.path[0], "plugins")]

def Tick():
	while True:
		try:
			if bot.need_reload.has_key('main') and bot.need_reload['main']:
				reload(ircbot)
				reload(settings)
				print "Collected %s objects out of %s. Garbarge are %s objects." % (gc.collect(2), 
					len(gc.get_objects()), len(gc.garbage))
				bot.need_reload['main'] = False
				bot.on_reload()

			bot.tick()
			#web_server.tick()

			time.sleep(0.1)
		except KeyboardInterrupt:
			print ""
			print "Entering debug mode, use c(ontinue) to exit. Don't stay here to long."
			pdb.set_trace()
		except:
			raise

# Run bot with debugger
pdb.run(Tick())
Ejemplo n.º 60
0
#coding=utf-8
python3 -m pdb xxx.py

输入l 显示源代码
输入n 向下执行一行代码
输入c continue继续执行代码
输入b和所在的行数 break添加断点
输入b 查看断点的序号
输入clear 断点的序号 清除断点
输入s 进入函数,展示调用函数的细节
输入p和变量 输出函数中变量的值
输入q 退出调试
输入r 快速执行到函数的最后一行

交互调试:
	import pdb
	pdb.run('testfun(args)')
程序中埋点:
	import pdb
	pdb.set_trace()