def process_argv(argv):
    """
    Process command-line arguments (minus argv[0]!), rearrange and execute.
    """
    # Initial preparation
    import __main__
    for (k, v) in global_constants.items():
        exec '%s = %s' % (k, v) in __main__.__dict__

    # Allow param.normalize_path.prefix to be overridden in the
    # startup files, but otherwise force it to exist before doing
    # anything else
    param.normalize_path.prefix = default_output_path()
    exec_startup_files()
    set_output_path(param.normalize_path.prefix)

    # Tell the user how many cores are in use, if available
    openmp_main = Parameterized(
        name="OpenMP")  # Dummy object just for messages
    try:
        import os, multiprocessing
        total_cores = multiprocessing.cpu_count()
        num_threads = int(os.environ.get('OMP_NUM_THREADS', total_cores))
        openmp_main.verbose(
            "Using %d threads on a machine with %d detected CPUs", num_threads,
            total_cores)
    except:
        pass

    # Repeatedly process options, if any, followed by filenames, if any, until nothing is left
    topo_parser.disable_interspersed_args()
    args = argv
    option = None
    global something_executed
    while True:
        # Process options up until the first filename
        (option, args) = topo_parser.parse_args(args, option)

        # Handle filename
        if args:
            filename = args.pop(0)
            #print "Executing %s" % (filename)
            filedir = os.path.dirname(os.path.abspath(filename))
            sys.path.insert(
                0, filedir)  # Allow imports relative to this file's path
            sim_name_from_filename(filename)  # Default value of topo.sim.name

            execfile(filename, __main__.__dict__)
            something_executed = True

        if not args:
            break

    global_params.check_for_unused_names()

    # If no scripts and no commands were given, pretend -i was given.
    if not something_executed: interactive()

    if option.gui: topo.guimain.title(topo.sim.name)

    ## INTERACTIVE SESSION BEGINS HERE (i.e. can't have anything but
    ## some kind of cleanup code afterwards)
    if os.environ.get('PYTHONINSPECT'):
        print "Output path: %s" % param.normalize_path.prefix
        print BANNER
        # CBALERT: should probably allow a way for users to pass
        # things to IPython? Or at least set up some kind of
        # topographica ipython config file. Right now, a topo_parser
        # option has to be added for every ipython option we want to
        # support (e.g. see --pdb)

        if ipython_shell_interface == "IPython.Shell":
            # IPython 0.10 and earlier

            # Stop IPython namespace hack?
            # http://www.nabble.com/__main__-vs-__main__-td14606612.html
            __main__.__name__ = "__mynamespace__"

            ipython_args = [
                '-noconfirm_exit', '-nobanner', '-pi1',
                CommandPrompt.get_format(), '-pi2',
                CommandPrompt2.get_format(), '-po',
                OutputPrompt.get_format()
            ]
            if option.pdb:
                ipython_args.append('-pdb')

            ipshell = IPShell(ipython_args, user_ns=__main__.__dict__)
            ipshell.mainloop(sys_exit=1)

        elif ipython_shell_interface == "InteractiveShellEmbed":
            # IPython 0.11 and later

            config = Config()

            if ipython_prompt_interface == "PromptManager":
                config.PromptManager.in_template = CommandPrompt.get_format()
                config.PromptManager.in2_template = CommandPrompt2.get_format()
                config.PromptManager.out_template = OutputPrompt.get_format()
            else:
                config.InteractiveShell.prompt_in1 = CommandPrompt.get_format()
                config.InteractiveShell.prompt_in2 = CommandPrompt2.get_format(
                )
                config.InteractiveShell.prompt_out = OutputPrompt.get_format()
            config.InteractiveShell.confirm_exit = False
            ipshell = IPShell(config=config,
                              user_ns=__main__.__dict__,
                              banner1="",
                              exit_msg="")
            if option.pdb:
                ipshell.call_pdb = True

            # Load Topographica IPython extension in embedded shell
            try:
                ipshell.extension_manager.load_extension('topo.misc.ipython')
            except:
                cmdline_main.warning(
                    "Could not load IPython extension 'topo.misc.ipython'; ignored error was:\n%s"
                    % traceback.format_exc())

            ipshell()

    global return_code
    if return_code != 0:
        cmdline_main.warning(
            "Errors encountered; exiting with return code %d" % return_code)

    sys.exit(return_code)
Example #2
0
def process_argv(argv):
    """
    Process command-line arguments (minus argv[0]!), rearrange and execute.
    """
    # Initial preparation
    import __main__
    for (k,v) in global_constants.items():
        exec '%s = %s' % (k,v) in __main__.__dict__

    # Allow param.normalize_path.prefix to be overridden in the
    # startup files, but otherwise force it to exist before doing
    # anything else
    param.normalize_path.prefix = default_output_path()
    exec_startup_files()
    set_output_path(param.normalize_path.prefix)

    # Tell the user how many cores are in use, if available
    openmp_main=Parameterized(name="OpenMP") # Dummy object just for messages
    try:
        import os,multiprocessing
        total_cores = multiprocessing.cpu_count()
        num_threads = int(os.environ.get('OMP_NUM_THREADS',total_cores))
        openmp_main.verbose("Using %d threads on a machine with %d detected CPUs" % (num_threads, total_cores))
    except:
        pass

    # Repeatedly process options, if any, followed by filenames, if any, until nothing is left
    topo_parser.disable_interspersed_args()
    args=argv
    option=None
    global something_executed
    while True:
        # Process options up until the first filename
        (option,args) = topo_parser.parse_args(args,option)

        # Handle filename
        if args:
            filename=args.pop(0)
            #print "Executing %s" % (filename)
            filedir = os.path.dirname(os.path.abspath(filename))
            sys.path.insert(0,filedir) # Allow imports relative to this file's path
            sim_name_from_filename(filename) # Default value of topo.sim.name

            execfile(filename,__main__.__dict__)
            something_executed=True

        if not args:
            break

    global_params.check_for_unused_names()

    # If no scripts and no commands were given, pretend -i was given.
    if not something_executed: interactive()

    if option.gui: topo.guimain.title(topo.sim.name)

    ## INTERACTIVE SESSION BEGINS HERE (i.e. can't have anything but
    ## some kind of cleanup code afterwards)
    if os.environ.get('PYTHONINSPECT'):
        print "Output path: %s" % param.normalize_path.prefix
        print BANNER
        # CBALERT: should probably allow a way for users to pass
        # things to IPython? Or at least set up some kind of
        # topographica ipython config file. Right now, a topo_parser
        # option has to be added for every ipython option we want to
        # support (e.g. see --pdb)

        if ipython_shell_interface == "IPython.Shell":
            # IPython 0.10 and earlier

            # Stop IPython namespace hack?
            # http://www.nabble.com/__main__-vs-__main__-td14606612.html
            __main__.__name__="__mynamespace__"

            ipython_args = ['-noconfirm_exit','-nobanner',
                            '-pi1',CommandPrompt.get_format(),
                            '-pi2',CommandPrompt2.get_format(),
                            '-po',OutputPrompt.get_format()]
            if option.pdb:
                ipython_args.append('-pdb')

            ipshell = IPShell(ipython_args,user_ns=__main__.__dict__)
            ipshell.mainloop(sys_exit=1)

        elif ipython_shell_interface == "InteractiveShellEmbed":
            # IPython 0.11 and later

            config = Config()

            if ipython_prompt_interface == "PromptManager":
                config.PromptManager.in_template = CommandPrompt.get_format()
                config.PromptManager.in2_template = CommandPrompt2.get_format()
                config.PromptManager.out_template = OutputPrompt.get_format()
            else:
                config.InteractiveShell.prompt_in1 = CommandPrompt.get_format()
                config.InteractiveShell.prompt_in2 = CommandPrompt2.get_format()
                config.InteractiveShell.prompt_out = OutputPrompt.get_format()
            config.InteractiveShell.confirm_exit = False
            ipshell = IPShell(config=config,user_ns=__main__.__dict__,
                              banner1="",exit_msg="")
            if option.pdb:
                ipshell.call_pdb = True

            # Load Topographica IPython extension in embedded shell
            ipshell.extension_manager.load_extension('topo.misc.ipython')
            ipshell()

    global return_code
    if return_code != 0:
        cmdline_main.warning("Errors encountered; exiting with return code %d" % return_code)

    sys.exit(return_code)