Process the command line arguments of this script and dispatch.
357141
def _main(args, prog_name):
  """"""
  # get options and arguments
  ui = getUI(prog_name, args)

  if ui.optionIsSet("test"):
    # just run unit tests
    unittest.main(argv=[sys.argv[0]])
  elif ui.optionIsSet("help"):
    # just show help
    ui.usage()
  else:
    verbose = ui.optionIsSet("verbose")

    # know there are exactly two arguments, because we specified this in the
    # UI description.
    regions_fn = ui.getArgument(0)
    to_count_fn = ui.getArgument(1)

    # get output handle
    out_fh = sys.stdout
    if ui.optionIsSet("output"):
      out_fh = open(ui.getValue("output"), "w")

    # norm?
    norm = ui.optionIsSet("normalize")

    # get anchor point
    anch = ANCHOR_START
    if ui.optionIsSet("anchor"):
      if ui.getValue("anchor") == "5-prime":
        anch = ANCHOR_5PRIME

    res = process_anchor_start(regions_fn, to_count_fn, anchor_to=anch,
                               normalize=norm, verbose=verbose)
    write_output(res, out_fh, verbose=verbose)
9317
def main(argv=None):
    '''  '''
    parser = get_parser()

    # Parse arguments and run the function
    global args
    args = parser.parse_args(argv)
    args.func()
992477
def execute(self, callback=None):
        
        # Preprocess options to extract --settings and --pythonpath.
        # These options could affect the commands that are available, so they
        # must be processed early.
        self.parser = parser = NewOptionParser(prog=self.prog_name,
                             usage=self.usage_info,
#                             version=self.get_version(),
                             formatter = NewFormatter(),
                             add_help_option = False,
                             option_list=self.option_list)
        
        if not self.global_options:
            global_options, args = parser.parse_args(self.argv)
            global_options.apps_dir = os.path.normpath(os.path.join(global_options.project, 'apps'))
            handle_default_options(global_options)
            args = args[1:]
        else:
            global_options = self.global_options
            args = self.argv

        if global_options.envs:
            for x in global_options.envs:
                if '=' in x:
                    k, v = x.split('=')
                    os.environ[k.strip()] = v.strip()
                else:
                    print ('Error: environment variable definition (%s) format is not right, '
                           'shoule be -Ek=v or -Ek="a b"' % x)

        global_options.settings = global_options.settings or os.environ.get('SETTINGS', 'settings.ini')
        global_options.local_settings = global_options.local_settings or os.environ.get('LOCAL_SETTINGS', 'local_settings.ini')
        
        if callback:
            callback(global_options)
            
        if len(args) == 0:
            if global_options.version:
                print self.get_version()
                sys.exit(0)
            else:
                self.print_help(global_options)
                sys.ext(1)

        self.do_command(args, global_options)
238196
def handle_cmd(self, cmd):
        """"""
        cmd = cmd.strip()
        segments = []
        for s in cmd.split():
            # remove bash-like comments
            if s.startswith('#'):
                break
            # TODO implement escape sequences (also for \#)
            segments.append(s)
        args = []
        if not len(segments):
            return
        # process more specific commands first
        while segments:
            cur_cmd = "_".join(segments)
            if cur_cmd in self._cmd_methods:
                argc = self._cmd_argc[cur_cmd]
                if argc is not None and len(args) != argc:
                    msg('command {0} expects {1} argument(s), got {2}',
                        " ".join(segments), argc, len(args))
                    return
                self._cmd_methods[cur_cmd](args)
                return
            args.insert(0, segments.pop())
        # invalid command
        prefix = '_'.join(args) + '_'
        matches = filter(
            lambda cmd: cmd.startswith(prefix), self._cmd_methods.keys())
        candidates = set([])
        for m in matches:
            if len(m) <= len(prefix):
                continue
            m = m[len(prefix):]
            if '_' in m:
                m = m[:m.index('_')]
            candidates.add(m)
        if len(candidates):
            msg('command "{0}" needs more arguments:', ' '.join(args))
            for c in candidates:
                msg('    {0}', c)
        else:
            msg('command "{0}" invalid; type ' +
                'help or use <TAB> for a list of commands',
                ' '.join(args))
1084641
def dispatch(cls, arguments, **kwargs):
        
        # first match wins
        # spec: all '-' elements must match, all others are False;
        #       '<sth>' elements are converted to call args on order of
        #       appearance
        #
        # kwargs are provided to dispatch call and used in func call
        for spec, func in cls._specs:
            # if command and arguments.get(command) and match(args):
            args = []  # specified args in order of appearance
            options = list(filter(lambda k: k.startswith('-') and
                                       (arguments[k] or k in spec),
                             arguments.keys()))
            cmds = list(filter(lambda k: not (k.startswith('-') or
                                         k.startswith('<')) and arguments[k],
                          arguments.keys()))
            args_spec = list(filter(lambda k: k.startswith('<'), spec))
            cmd_spec = list(filter(lambda k: not (k.startswith('-') or
                                             k.startswith('<')), spec))
            for element in spec:
                if element.startswith('-'):
                    # element is an option
                    if element in options:
                        args.append(arguments.get(element, False))
                        options.remove(element)
                elif element.startswith('<') and \
                        not arguments.get(element) is False:
                    # element is an argument
                    args.append(arguments.get(element))
                    if element in args_spec:
                        args_spec.remove(element)
                else:
                    # element is a command
                    if element in cmds and element in cmd_spec:
                        cmds.remove(element)
                        cmd_spec.remove(element)

            if options:
                continue  # not all options have been matched
            if cmds:
                continue  # not all cmds from command line have been matched
            if args_spec:
                continue  # not all args from spec have been provided
            if cmd_spec:
                continue  # not all cmds from spec have been provided
            # all options and cmds matched : call the cmd
            # TODO leave out all args to deal with "empty" signature
            exit_code = func(*args, **kwargs)
            return exit_code
        # no matching spec found
        raise Exception('No implementation for spec: %s' % arguments)
1056158
void dispatch(String line, DispatchCallback callback) {
    if (line == null) {
      // exit
      exit = true;
      return;
    }

    if (line.trim().length() == 0) {
      callback.setStatus(DispatchCallback.Status.SUCCESS);
      return;
    }

    if (isComment(line)) {
      callback.setStatus(DispatchCallback.Status.SUCCESS);
      return;
    }

    line = line.trim();

    if (isHelpRequest(line)) {
      line = COMMAND_PREFIX + "help";
    }

    final boolean echoToFile;
    if (line.startsWith(COMMAND_PREFIX)) {
      Map<String, CommandHandler> cmdMap = new TreeMap<>();
      String commandLine = line.substring(1);
      for (CommandHandler commandHandler : getCommandHandlers()) {
        String match = commandHandler.matches(commandLine);
        if (match != null) {
          cmdMap.put(match, commandHandler);
        }
      }

      final CommandHandler matchingHandler;
      switch (cmdMap.size()) {
      case 0:
        callback.setStatus(DispatchCallback.Status.FAILURE);
        error(loc("unknown-command", commandLine));
        return;
      case 1:
        matchingHandler = cmdMap.values().iterator().next();
        break;
      default:
        // look for the exact match
        matchingHandler = cmdMap.get(split(commandLine, 1)[0]);
        if (matchingHandler == null) {
          callback.setStatus(DispatchCallback.Status.FAILURE);
          error(loc("multiple-matches", cmdMap.keySet().toString()));
          return;
        }
        break;
      }

      echoToFile = matchingHandler.echoToFile();
      callback.setStatus(DispatchCallback.Status.RUNNING);
      matchingHandler.execute(commandLine, callback);
    } else {
      echoToFile = true;
      callback.setStatus(DispatchCallback.Status.RUNNING);
      commands.sql(line, callback);
    }

    // save it to the current script, if any
    if (scriptOutputFile != null && echoToFile) {
      scriptOutputFile.addLine(line);
    }

  }
679620
def main():
    """"""
    parser = argparse.ArgumentParser()
    group_tcp = parser.add_argument_group('TCP')
    group_tcp.add_argument('--tcp', dest='mode', action='store_const', const=PROP_MODE_TCP, help="Set tcp mode")
    group_tcp.add_argument('--host', dest='hostname', help="Specify hostname", default='')
    group_tcp.add_argument('--port', dest='port', help="Specify port", default=23, type=int)
    group_serial = parser.add_argument_group('Serial')
    group_serial.add_argument('--serial', dest='mode', action='store_const', const=PROP_MODE_SERIAL, help="Set serial mode")
    group_serial.add_argument('--interface', dest='interface', help="Specify interface", default='')
    group_file = parser.add_argument_group('File')
    group_file.add_argument('--file', dest='mode', action='store_const', const=PROP_MODE_FILE, help="Set file mode")
    group_file.add_argument('--name', dest='file', help="Specify file name", default='')
    args = parser.parse_args()

    kwb = KWBEasyfire(args.mode, args.hostname, args.port, args.interface, 0, args.file)
    kwb.run_thread()
    time.sleep(5)
    kwb.stop_thread()
    print(kwb)
954398
def execute
      cli_arguments = Telegram::CLIArguments.new(@config)
      command = "'#{@config.daemon}' #{cli_arguments.to_s}"
      @stdout = IO.popen(command, 'a+')
      initialize_stdout_reading
    end
816819
def run_from_argv(self, prog, subcommand, global_options, argv):
        
        self.prog_name = prog
        if self.skip_options:
            parser = NewOptionParser(prog=self.prog_name,
                     usage=self.usage(subcommand),
                    version='',
                    formatter = NewFormatter(),
                     add_help_option = False,
                     option_list=self.option_list)
        else:
            parser = self.create_parser(prog, subcommand)
        options, args = parser.parse_args(argv)
        self.execute(args, options, global_options)
1252725
function processArgv(argv) {
  let command = getCommand(argv);
  let isInternalCommand = true;

  logger.info(`SKY UX processing command ${command}`);

  switch (command) {
    case 'version':
      require('./lib/version').logVersion(argv);
      break;
    case 'new':
      require('./lib/new')(argv);
      break;
    case 'help':
      require('./lib/help')(argv);
      break;
    case 'install':
      require('./lib/install')(argv);
      break;
    default:
      isInternalCommand = false;
  }

  invokeCommand(command, argv, isInternalCommand);
}
1139484
static void processArgs(String[] args, final PrintStream out) {
        Options options = buildOptions();

        try {
            CommandLine cmd = parseCommandLine(options, args);

            if (cmd.hasOption('h')) {
                printHelp(out, options);
            } else if (cmd.hasOption('v')) {
                String version = GroovySystem.getVersion();
                out.println("Groovy Version: " + version + " JVM: " + System.getProperty("java.version") + 
                        " Vendor: " + System.getProperty("java.vm.vendor")  + " OS: " + System.getProperty("os.name"));
            } else {
                // If we fail, then exit with an error so scripting frameworks can catch it
                // TODO: pass printstream(s) down through process
                if (!process(cmd)) {
                    System.exit(1);
                }
            }
        } catch (ParseException pe) {
            out.println("error: " + pe.getMessage());
            printHelp(out, options);
        } catch (IOException ioe) {
            out.println("error: " + ioe.getMessage());
        }
    }
105738
def main():
    """"""
    # Dynamically determine all the providers available and gather command line arguments.
    parsed_args = generate_cli_main_parser().parse_args()

    log_level = logging.getLevelName(parsed_args.log_level)
    logging.basicConfig(stream=sys.stdout, level=log_level,
                        format='%(message)s')
    logger.debug('Arguments: %s', parsed_args)

    # In the CLI context, will get configuration interactively:
    #   * from the command line
    #   * from the environment variables
    #   * from lexicon configuration files found in given --config-dir (default is current dir)
    config = ConfigResolver()
    config.with_args(parsed_args).with_env().with_config_dir(parsed_args.config_dir)

    client = Client(config)

    results = client.execute()

    handle_output(results, parsed_args.output, config.resolve('lexicon:action'))
966138
def go():
    """"""
    parser = argparse.ArgumentParser(prog='PROG', epilog=help_epilog,
                                     formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument('-V', '--version', action='store_true',
                        help="show version and info about the system, and exit")
    parser.add_argument('-v', '--verbose', action='store_true',
                        help="send all internal debugging lines to stderr, which may be very "
                             "useful to debug any problem that may arise.")
    parser.add_argument('-q', '--quiet', action='store_true',
                        help="don't show anything (unless it has a real problem), so the "
                             "original script stderr is not polluted at all.")
    parser.add_argument('-d', '--dependency', action='append',
                        help="specify dependencies through command line (this option can be "
                             "used multiple times)")
    parser.add_argument('-r', '--requirement', action='append',
                        help="indicate files to read dependencies from (this option can be "
                             "used multiple times)")
    parser.add_argument('-p', '--python', action='store',
                        help=("Specify the Python interpreter to use.\n"
                              " Default is: %s") % (sys.executable,))
    parser.add_argument('-x', '--exec', dest='executable', action='store_true',
                        help=("Indicate that the child_program should be looked up in the "
                              "virtualenv."))
    parser.add_argument('-i', '--ipython', action='store_true', help="use IPython shell.")
    parser.add_argument('--system-site-packages', action='store_true', default=False,
                        help=("Give the virtual environment access to the "
                              "system site-packages dir."))
    parser.add_argument('--virtualenv-options', action='append', default=[],
                        help=("Extra options to be supplied to virtualenv. (this option can be "
                              "used multiple times)"))
    parser.add_argument('--check-updates', action='store_true',
                        help=("check for packages updates"))
    parser.add_argument('--no-precheck-availability', action='store_true',
                        help=("Don't check if the packages exists in PyPI before actually try "
                              "to install them."))
    parser.add_argument('--pip-options', action='append', default=[],
                        help=("Extra options to be supplied to pip. (this option can be "
                              "used multiple times)"))
    parser.add_argument('--python-options', action='append', default=[],
                        help=("Extra options to be supplied to python. (this option can be "
                              "used multiple times)"))
    parser.add_argument('--rm', dest='remove', metavar='UUID',
                        help=("Remove a virtualenv by UUID. See --get-venv-dir option to "
                              "easily find out the UUID."))
    parser.add_argument('--clean-unused-venvs', action='store',
                        help=("This option remove venvs that haven't been used for more than "
                              "CLEAN_UNUSED_VENVS days. Appart from that, will compact usage "
                              "stats file.\n"
                              "When this option is present, the cleaning takes place at the "
                              "beginning of the execution."))
    parser.add_argument('--get-venv-dir', action='store_true',
                        help=("Show the virtualenv base directory (which includes the "
                              "virtualenv UUID) and quit."))
    parser.add_argument('child_program', nargs='?', default=None)
    parser.add_argument('child_options', nargs=argparse.REMAINDER)

    cli_args = _get_normalized_args(parser)

    # update args from config file (if needed).
    args = file_options.options_from_file(cli_args)

    # validate input, parameters, and support some special options
    if args.version:
        print("Running 'fades' version", fades.__version__)
        print("    Python:", sys.version_info)
        print("    System:", platform.platform())
        return 0

    # set up logger and dump basic version info
    logger = fades_logger.set_up(args.verbose, args.quiet)
    logger.debug("Running Python %s on %r", sys.version_info, platform.platform())
    logger.debug("Starting fades v. %s", fades.__version__)
    logger.debug("Arguments: %s", args)

    # verify that the module is NOT being used from a virtualenv
    if detect_inside_virtualenv(sys.prefix, getattr(sys, 'real_prefix', None),
                                getattr(sys, 'base_prefix', None)):
        logger.error(
            "fades is running from inside a virtualenv (%r), which is not supported", sys.prefix)
        raise FadesError("Cannot run from a virtualenv")

    if args.verbose and args.quiet:
        logger.warning("Overriding 'quiet' option ('verbose' also requested)")

    # start the virtualenvs manager
    venvscache = cache.VEnvsCache(os.path.join(helpers.get_basedir(), 'venvs.idx'))
    # start usage manager
    usage_manager = envbuilder.UsageManager(os.path.join(helpers.get_basedir(), 'usage_stats'),
                                            venvscache)

    if args.clean_unused_venvs:
        try:
            max_days_to_keep = int(args.clean_unused_venvs)
        except ValueError:
            logger.error("clean_unused_venvs must be an integer.")
            raise FadesError('clean_unused_venvs not an integer')

        usage_manager.clean_unused_venvs(max_days_to_keep)
        return 0

    uuid = args.remove
    if uuid:
        venv_data = venvscache.get_venv(uuid=uuid)
        if venv_data:
            # remove this venv from the cache
            env_path = venv_data.get('env_path')
            if env_path:
                envbuilder.destroy_venv(env_path, venvscache)
            else:
                logger.warning("Invalid 'env_path' found in virtualenv metadata: %r. "
                               "Not removing virtualenv.", env_path)
        else:
            logger.warning('No virtualenv found with uuid: %s.', uuid)
        return 0

    # decided which the child program really is
    analyzable_child_program, child_program = decide_child_program(
        args.executable, args.child_program)

    # Group and merge dependencies
    indicated_deps = consolidate_dependencies(args.ipython,
                                              analyzable_child_program,
                                              args.requirement,
                                              args.dependency)

    # Check for packages updates
    if args.check_updates:
        helpers.check_pypi_updates(indicated_deps)

    # get the interpreter version requested for the child_program
    interpreter, is_current = helpers.get_interpreter_version(args.python)

    # options
    pip_options = args.pip_options  # pip_options mustn't store.
    python_options = args.python_options
    options = {}
    options['pyvenv_options'] = []
    options['virtualenv_options'] = args.virtualenv_options
    if args.system_site_packages:
        options['virtualenv_options'].append("--system-site-packages")
        options['pyvenv_options'] = ["--system-site-packages"]

    create_venv = False
    venv_data = venvscache.get_venv(indicated_deps, interpreter, uuid, options)
    if venv_data:
        env_path = venv_data['env_path']
        # A venv was found in the cache check if its valid or re-generate it.
        if not os.path.exists(env_path):
            logger.warning("Missing directory (the virtualenv will be re-created): %r", env_path)
            venvscache.remove(env_path)
            create_venv = True
    else:
        create_venv = True

    if create_venv:
        # Check if the requested packages exists in pypi.
        if not args.no_precheck_availability and indicated_deps.get('pypi'):
            logger.info("Checking the availabilty of dependencies in PyPI. "
                        "You can use '--no-precheck-availability' to avoid it.")
            if not helpers.check_pypi_exists(indicated_deps):
                logger.error("An indicated dependency doesn't exist. Exiting")
                raise FadesError("Required dependency does not exist")

        # Create a new venv
        venv_data, installed = envbuilder.create_venv(indicated_deps, args.python, is_current,
                                                      options, pip_options)
        # store this new venv in the cache
        venvscache.store(installed, venv_data, interpreter, options)

    if args.get_venv_dir:
        # all it was requested is the virtualenv's path, show it and quit (don't run anything)
        print(venv_data['env_path'])
        return 0

    # run forest run!!
    python_exe = 'ipython' if args.ipython else 'python'
    python_exe = os.path.join(venv_data['env_bin_path'], python_exe)

    # add the virtualenv /bin path to the child PATH.
    environ_path = venv_data['env_bin_path']
    if 'PATH' in os.environ:
        environ_path += os.pathsep + os.environ['PATH']
    os.environ['PATH'] = environ_path

    # store usage information
    usage_manager.store_usage_stat(venv_data, venvscache)
    if child_program is None:
        interactive = True
        logger.debug(
            "Calling the interactive Python interpreter with arguments %r", python_options)
        cmd = [python_exe] + python_options
        p = subprocess.Popen(cmd)
    else:
        interactive = False
        if args.executable:
            cmd = [os.path.join(venv_data['env_bin_path'], child_program)]
            logger.debug("Calling child program %r with options %s",
                         child_program, args.child_options)
        else:
            cmd = [python_exe] + python_options + [child_program]
            logger.debug(
                "Calling Python interpreter with arguments %s to execute the child program"
                " %r with options %s", python_options, child_program, args.child_options)

        try:
            p = subprocess.Popen(cmd + args.child_options)
        except FileNotFoundError:
            logger.error("Command not found: %s", child_program)
            raise FadesError("Command not found")

    def _signal_handler(signum, _):
        """Handle signals received by parent process, send them to child.

        The only exception is CTRL-C, that is generated *from* the interactive
        interpreter (it's a keyboard combination!), so we swallow it for the
        interpreter to not see it twice.
        """
        if interactive and signum == signal.SIGINT:
            logger.debug("Swallowing signal %s", signum)
        else:
            logger.debug("Redirecting signal %s to child", signum)
            os.kill(p.pid, signum)

    # redirect the useful signals
    for s in REDIRECTED_SIGNALS:
        signal.signal(s, _signal_handler)

    # wait child to finish, end
    rc = p.wait()
    if rc:
        logger.debug("Child process not finished correctly: returncode=%d", rc)
    return rc
779501
def process_args(self, args):
		
		shutit_global.shutit_global_object.yield_to_draw()
		assert isinstance(args,ShutItInit), shutit_util.print_debug()

		if args.action == 'version':
			shutit_global.shutit_global_object.shutit_print('ShutIt version: ' + shutit.shutit_version)
			shutit_global.shutit_global_object.handle_exit(exit_code=0)

		# What are we asking shutit to do?
		self.action['list_configs'] = args.action == 'list_configs'
		self.action['list_modules'] = args.action == 'list_modules'
		self.action['list_deps']    = args.action == 'list_deps'
		self.action['skeleton']     = args.action == 'skeleton'
		self.action['build']        = args.action == 'build'
		self.action['run']          = args.action == 'run'

		# Logging
		if not self.logging_setup_done:
			self.logfile  = args.logfile
			self.loglevel = args.loglevel
			if self.loglevel is None or self.loglevel == '':
				self.loglevel = 'INFO'
			self.setup_logging()
		shutit_global.shutit_global_object.setup_panes(action=args.action)

		# This mode is a bit special - it's the only one with different arguments
		if self.action['skeleton']:
			self.handle_skeleton(args)
			shutit_global.shutit_global_object.handle_exit()
		elif self.action['run']:
			self.handle_run(args)
			sys.exit(0)
		elif self.action['build'] or self.action['list_configs'] or self.action['list_modules']:
			self.handle_build(args)
		else:
			self.fail('Should not get here: action was: ' + str(self.action))
		self.nocolor = args.nocolor
57819
def execute(self):
        
        # Ensure that we have commands registered
        if not self.commands or self._parser is None:
            raise NotImplementedError(
                "No commands registered with this program!"
            )

        # Handle input from the command line
        args = self.parser.parse_args()                # Parse the arguments

        try:

            handle_default_args(args)                  # Handle the default args

            if not hasattr(args, 'func'):              # Handle no subcommands
                self.parser.print_help()
                self.exit(0)

            msg = args.func(args)                      # Call the default function
            msg = "{}\n".format(msg) if msg else ''    # Format the message
            self.exit(0, msg)                          # Exit cleanly with message

        except Exception as e:
            if hasattr(args, 'traceback') and args.traceback:
                traceback.print_exc()

            msg = color.format(str(e), color.RED)
            self.exit(1, msg)
1306117
def dispatch_command(self, command, params=None):
        """"""
        try:
            if command in self.handlers:
                self.handlers[command](**params)
            else:
                logging.warning('Unsupported command: %s: %s',
                                command, params)
        except Exception as e:
            logging.warning('Error during command execution',
                            exc_info=sys.exc_info())
            raise e
74848
protected function doProcess(): void
    {
        $module = Request::getModule();
        $controller = Request::getController();
        $params = Request::getParams();

        try {
            // try to dispatch controller
            $result = $this->dispatch($module, $controller, $params);
        } catch (ForbiddenException $e) {
            // dispatch default error controller
            $result = $this->forbidden($e);
        } catch (RedirectException $e) {
            // should return `null` for disable output and setup redirect headers
            $result = $this->redirect($e);
        } catch (\Exception $e) {
            // dispatch default error controller
            $result = $this->error($e);
        }

        // setup layout, if needed
        if ($this->useLayout()) {
            // render view to layout
            // needed for headScript and headStyle helpers
            Layout::setContent($result->render());
            Response::setBody(Layout::getInstance());
        } else {
            Response::setBody($result);
        }
    }