Parse comand line arguments/flags and run program
546607
def run(self, args=None):
        

        args = args or self.parser.parse_args()
        super(Program, self).run(args)

        # Read configuration file if any
        if args.config is not None:
            filepath = args.config
            self.config.read(filepath)

        # Start workers then wait until they finish work
        [w.start() for w in self.workers]
        [w.join() for w in self.workers]
208242
def run(path, code=None, params=None, **meta):
        
        import _ast

        builtins = params.get("builtins", "")

        if builtins:
            builtins = builtins.split(",")

        tree = compile(code, path, "exec", _ast.PyCF_ONLY_AST)
        w = checker.Checker(tree, path, builtins=builtins)
        w.messages = sorted(w.messages, key=lambda m: m.lineno)
        return [{
            'lnum': m.lineno,
            'text': m.message % m.message_args,
            'type': m.message[0]
        } for m in w.messages]
492174
def main(argv=None):
    """"""
   
    program_name = __programm_name__
    program_version = "v%s" % __version__
    program_descrption = __programm_description__

    try:
        # Setup argument parser
        parser = ArgumentParser(prog=program_name, description=program_descrption)
        parser.add_argument("-v", "--verbose", dest="verbose", action="count", help="run in verbose mode (-vvv for more, -vvvv to enable connection debugging)")
        parser.add_argument("-s", "--sudo", action="store_true", help="run supervisorctl actions with sudo (nopasswd))")
        parser.add_argument("-V", "--version", action="version", version=program_version)
        parser.add_argument("host-pattern", help="A host-pattern usually refers to a group of hosts. For more details, see Ansible documentation about Patterns.")
        #parser.add_argument("supervisorctl-action", help="A supervisorctl action (and optional argument). For more details, see Supervisor documentation about the available supervisorctl actions.")
        
        subparsers = parser.add_subparsers(help="One of the available supervisorctl actions.", dest="supervisorctl-action")
        subparsers.add_parser("status", help="Get status info of all processes.")
        subparsers.add_parser("reread", help="Reread the configuration files of supervisord")
        subparsers.add_parser("reload", help="Restart remote supervisord")
        subparsers.add_parser("update", help="Reload the configuration files of supervisord and add/remove processes as necessary")
        start_subparser = subparsers.add_parser("start", help="Start a process by name")
        start_subparser.add_argument("process-name", help="Name of the process")
        stop_subparser = subparsers.add_parser("stop", help="Stop a process by name")
        stop_subparser.add_argument("process-name", help="Name of the process")
        restart_subparser = subparsers.add_parser("restart", help="Restart a process by name")
        restart_subparser.add_argument("process-name", help="Name of the process")
        remove_subparser = subparsers.add_parser("remove", help="Remove a process by name")
        remove_subparser.add_argument("process-name", help="Name of the process")
        
        # Process arguments
        args = parser.parse_args(argv)
        verbose = args.verbose
        host_pattern = getattr(args, "host-pattern")
        supervisorctl_action = getattr(args, "supervisorctl-action")        
        
        sudo = args.sudo
        ansible_executable = "ansible"
        supervisorctl_executable = "supervisorctl"
        ansible_action_option = "-a"
        
        if sudo:
            supervisorctl_command = "sudo " + supervisorctl_executable + " " + supervisorctl_action
        else:
            supervisorctl_command = supervisorctl_executable + " " + supervisorctl_action
          
        if supervisorctl_action not in ['status', 'reread', 'update', 'reload']:
            supervisorctl_argument = getattr(args, "process-name")
            supervisorctl_command = supervisorctl_command + ' ' + supervisorctl_argument
            
        if verbose >0:
            verbose_level = "-"+ "v"*verbose
            print("Verbose mode on: " + verbose_level)
            print "Parsed arguments:"
            print args   
            retcode = call([ansible_executable, host_pattern, verbose_level, ansible_action_option, supervisorctl_command,])
        else:
            retcode = call([ansible_executable, host_pattern, ansible_action_option, supervisorctl_command])
        
        return retcode
    except KeyboardInterrupt:
        ### handle keyboard interrupt ###
        return 0
541830
def parse_args():
    """"""
    parser = arguments.parser(__doc__)
    parser.args('streams', help='streams to use')
    parser.opt('-p', '--paste', 'paste text from clipboard')
    parser.opt('-i', '--stdin', 'wait for text from stdin')
    return parser.parse_args()
984738
def main():
    """"""

    parser = argparse.ArgumentParser(description='Extract parameters from an ULog file')
    parser.add_argument('filename', metavar='file.ulg', help='ULog input file')

    parser.add_argument('-d', '--delimiter', dest='delimiter', action='store',
                        help='Use delimiter in CSV (default is \',\')', default=',')

    parser.add_argument('-i', '--initial', dest='initial', action='store_true',
                        help='Only extract initial parameters', default=False)

    parser.add_argument('-o', '--octave', dest='octave', action='store_true',
                        help='Use Octave format', default=False)

    parser.add_argument('-t', '--timestamps', dest='timestamps', action='store_true',
                        help='Extract changed parameters with timestamps', default=False)

    parser.add_argument('output_filename', metavar='params.txt',
                        type=argparse.FileType('w'), nargs='?',
                        help='Output filename (default=stdout)', default=sys.stdout)

    args = parser.parse_args()
    ulog_file_name = args.filename

    message_filter = []
    if not args.initial: message_filter = None

    ulog = ULog(ulog_file_name, message_filter)

    param_keys = sorted(ulog.initial_parameters.keys())
    delimiter = args.delimiter
    output_file = args.output_filename

    if not args.octave:
        for param_key in param_keys:
            output_file.write(param_key)
            if args.initial:
                output_file.write(delimiter)
                output_file.write(str(ulog.initial_parameters[param_key]))
                output_file.write('\n')
            elif args.timestamps:
                output_file.write(delimiter)
                output_file.write(str(ulog.initial_parameters[param_key]))
                for t, name, value in ulog.changed_parameters:
                    if name == param_key:
                        output_file.write(delimiter)
                        output_file.write(str(value))

                output_file.write('\n')
                output_file.write("timestamp")
                output_file.write(delimiter)
                output_file.write('0')
                for t, name, value in ulog.changed_parameters:
                    if name == param_key:
                        output_file.write(delimiter)
                        output_file.write(str(t))

                output_file.write('\n')
            else:
                for t, name, value in ulog.changed_parameters:
                    if name == param_key:
                        output_file.write(delimiter)
                        output_file.write(str(value))

                output_file.write('\n')

    else:

        for param_key in param_keys:
            output_file.write('# name ')
            output_file.write(param_key)
            values = [ulog.initial_parameters[param_key]]

            if not args.initial:
                for t, name, value in ulog.changed_parameters:
                    if name == param_key:
                        values += [value]

            if len(values) > 1:
                output_file.write('\n# type: matrix\n')
                output_file.write('# rows: 1\n')
                output_file.write('# columns: ')
                output_file.write(str(len(values)) + '\n')
                for value in values:
                    output_file.write(str(value) + ' ')

            else:
                output_file.write('\n# type: scalar\n')
                output_file.write(str(values[0]))

            output_file.write('\n')
1153502
def _parse_args():
    """"""
    class HelpOnErrorArgParser(argparse.ArgumentParser):
        """Print help message as well when an error is raised."""
        def error(self, message):
            sys.stderr.write("Error: %s\n" % message)
            self.print_help()
            sys.exit(2)

    def validate(_file):
        """Validate if the given target argument is a valid file or a valid directory"""
        _file = abspath(_file)
        if not exists(_file):
            if not exists(dirname(_file)):
                # Argparse uses the ArgumentTypeError to give a rejection message like:
                # error: argument input: x does not exist
                raise argparse.ArgumentTypeError("{0} does not exist".format(_file))
        return _file

    def expand_cg_args(cg_args):
        """Separate clubbed flags in command line args for the generator.py

        Allows flags to be clubbed like, -ilt example.txt.
        """
        expanded = list()
        for item in cg_args:
            if len(item) < 3:
                # If at all a flag, must be single flag
                expanded.append(item)
                continue
            if item.startswith("-"):
                if not item.startswith("--"):
                    for flag in item[1:]:
                        expanded.append('-' + flag)
                    continue
            expanded.append(item)
        return expanded

    class AssignDefaultIgnore(argparse.Action):
        """If argument is specified but nothing provided, use pre-defined.

        nargs="*" doesn't allow const and default kwarg can't be used as we might not want to
        ignore as well.
        """
        def __call__(self, parser, args, values, option_string=None):
            if values is not None and not len(values):
                values = IGNORE_METHODS
            setattr(args, self.dest, values)

    try:
        indx = sys.argv.index('--')
        cg_args, sys.argv = sys.argv[1:indx], sys.argv[:1] + sys.argv[indx + 1:]
    except ValueError:
        cg_args = []

    cg_args = expand_cg_args(cg_args)  # allow -il type of usage
    parser = HelpOnErrorArgParser(description=DESCRIPTION)
    parser.add_argument(
        "-l", "--long", action='store_true', default=False,
        help="File reference of method in call graph is absolute, i.e. starts with ansible, "
             "otherwise just the basename if not __init__.py")
    parser.add_argument(
        "-t", "--target", nargs="?", type=validate, const=TARGET_FILE, default=TARGET_FILE,
        help="Filepath to write call graph, defaults to %(default)s")
    parser.add_argument(
        "-i", "--ignore", nargs='*', action=AssignDefaultIgnore,
        help="Methods to ignore while generating call graph")
    # TODO: Aloow classes that can be intercepted
    parser.usage = \
        parser.format_usage()[len("usage: "):].rstrip() + " -- <ansible-playbook options>\n"
    cg_args = parser.parse_args(cg_args)

    if not len(sys.argv[1:]):
        parser.print_help()
        sys.exit(2)

    return cg_args
1275155
function handleflags($i, $argv)
    {
        if (!isset($argv[1]) || !isset(self::$_options[$argv[$i][1]])) {
            throw new Exception('Command line syntax error: undefined option "' .  $argv[$i] . '"');
        }
        $v = self::$_options[$argv[$i][1]] == '-';
        if (self::$_options[$argv[$i][1]]['type'] == self::OPT_FLAG) {
            $this->{self::$_options[$argv[$i][1]]['arg']} = 1;
        } elseif (self::$_options[$argv[$i][1]]['type'] == self::OPT_FFLAG) {
            $this->{self::$_options[$argv[$i][1]]['arg']}($v);
        } elseif (self::$_options[$argv[$i][1]]['type'] == self::OPT_FSTR) {
            $this->{self::$_options[$argv[$i][1]]['arg']}(substr($v, 2));
        } else {
            throw new Exception('Command line syntax error: missing argument on switch: "' . $argv[$i] . '"');
        }
        return 0;
    }
424320
def run(line):
    
    arguments = shlex.split(line)
    path = lookup(arguments[0])  # Lookup the first arguments in PATH
    execute(path, arguments)
291090
def main(argv=None):
    
    # Get command line arguments, validate them, and normalize them
    opts = cmdparse.parse_args(argv)
    assert validate_opts.validate(opts)
    opts = normalize_opts.normalize(opts)

    if opts.verbose:
        # Update client: print input and output directories
        messages.print_input_output(opts)

    file_paths = fileparse.get_file_list(opts)
    assert validate_files.validate(file_paths, opts)

    if opts.verbose and opts.is_dir:
        # Update client: print files that will be parsed
        messages.print_files(opts, file_paths)

    # For now, only using default GitHub Markdown for parsing
    # Collect tag/anchor combinations
    collector = make_github_markdown_collector(opts)
    anchors, duplicate_tags = collector.collect(file_paths)
    assert validate_anchors.validate(anchors, duplicate_tags, opts)

    # Write files using previously found AnchorHub tags and generated anchors
    writer = make_github_markdown_writer(opts)
    counter = writer.write(file_paths, anchors, opts)

    if opts.verbose:
        if opts.is_dir:
            # Update client: print files that had modifications
            messages.print_modified_files(opts, anchors)
        # Print summary statistics
        messages.print_summary_stats(counter)
199356
def parse_command_line
      begin
        opts = GetoptLong.new(
          [ '--tag', '-t', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--tag-use-and', '-a', GetoptLong::NO_ARGUMENT ],
          [ '--tag-use-or', '-o', GetoptLong::NO_ARGUMENT ],
          [ '--array', '-r', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--deployment', '-e', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--script', '-s', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--ssh', '-x', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--input', '-i', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-template', '-m', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--set-tag', '-w', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--report', '-b', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--progress', '-p', GetoptLong::NO_ARGUMENT ],
          [ '--verbose', '-v', GetoptLong::NO_ARGUMENT ],
          [ '--quiet', '-q', GetoptLong::NO_ARGUMENT ],
          [ '--noprompt', '-z', GetoptLong::NO_ARGUMENT ],
          [ '--concurrency', '-c', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--delay', '-d', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--retry', '-y', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--hold', '-7', GetoptLong::NO_ARGUMENT ],
          [ '--dry-run', '-n', GetoptLong::NO_ARGUMENT ],
          [ '--limit', '-l', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--version', '-1', GetoptLong::NO_ARGUMENT ],
          [ '--chimpd', '-f', GetoptLong::OPTIONAL_ARGUMENT ],
          [ '--chimpd-wait-until-done', '-j', GetoptLong::NO_ARGUMENT ],
          [ '--dont-check-templates', '-0', GetoptLong::NO_ARGUMENT ],
          [ '--ignore-errors', '-9', GetoptLong::NO_ARGUMENT ],
          [ '--ssh-user', '-u', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--help', '-h', GetoptLong::NO_ARGUMENT ],
          [ '--group', '-g', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-type', '-2', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--group-concurrency', '-3', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timing-log', '-4', GetoptLong::REQUIRED_ARGUMENT ],
          [ '--timeout', '-5',  GetoptLong::REQUIRED_ARGUMENT ],
          [ '--noverify', '-6', GetoptLong::NO_ARGUMENT ],
          [ '--exact-matching', '-8', GetoptLong::NO_ARGUMENT ],
          [ '--job-notes', '-k', GetoptLong::OPTIONAL_ARGUMENT ]
        )

        opts.each do |opt, arg|
          case opt
            when '--help', '-h'
              help
              exit 0
            when '--tag', '-t'
              @tags << arg
            when '--tag-use-and', '-a'
              @match_all = true
            when '--tag-use-or', '-o'
              @match_all = false
            when '--array', '-a'
              @array_names << arg
            when '--deployment', '-e'
              @deployment_names << arg
            when '--template', '-m'
              @template = arg
            when '--script', '-s'
              set_action(:action_rightscript)
              if arg == ""
                # Empty but not nil means show list of operational scripts to choose from
                @script = ""
              else
                @script = arg
              end
            when '--ssh', '-x'
              set_action(:action_ssh)
              @break_array_into_instances = true
              if arg == ""
                print "Enter SSH command line to execute: "
                @ssh = gets.chomp
              else
                @ssh = arg
              end
            when '--ssh-user', '-u'
              @ssh_user = arg
            when '--input', '-i'
              arg =~ /(.+)=(.+)/
              @inputs[$1]=$2
            when '--set-template', '-m'
              set_action(:action_set)
              @template = arg
            when '--set-tag', '-w'
              set_action(:action_set)
              @set_tags << arg
            when '--report', '-b'
              set_action(:action_report)
              @report = arg
              @@verbose = false
              @@quiet = true
              @break_array_into_instances = true
              @concurrency = 5 if @concurrency == 1
            when '--progress', '-p'
              @progress = @progress ? false : true
            when '--noprompt', '-z'
              @prompt = false
            when '--concurrency', '-c'
              @concurrency = arg.to_i
            when '--delay', '-d'
              @delay = arg.to_i
            when '--hold', '-7'
              @hold = true
            when '--retry', '-y'
              @retry_count = arg.to_i
            when '--limit', '-l'
              @limit_start, @limit_end = arg.split(',')
            when '--verbose', '-v'
              @@verbose = true
              Log.threshold = Logger::DEBUG
            when '--quiet', '-q'
              @@quiet = true
            when '--dont-check-templates', '-0'
              @dont_check_templates_for_script = true
            when '--version'
              puts VERSION
              exit 0
            when '--chimpd'
              @use_chimpd = true
              unless arg.empty?
                if arg =~ /[\d]+\.[\d]+\.[\d]+\.[\d]+:[\d]+/
                  @chimpd_host, @chimpd_port = arg.split(':')
                  @chimpd_port = @chimpd_port.to_i
                else
                  @chimpd_port = arg.to_i
                end
              end
            when '--chimpd-wait-until-done'
              @use_chimpd = true
              @chimpd_wait_until_done = true
            when '--dry-run', '-n'
              @dry_run = true
            when '--ignore-errors', '-9'
              @ignore_errors = true
            when '--group', '-g'
              @group = arg.to_sym
            when '--group-type'
              @group_type = arg.to_sym
            when '--group-concurrency'
              @group_concurrency = arg.to_i
            when '--job-notes'
              @job_notes = arg
            when '--timing-log'
              @timing_log = arg
            when '--timeout'
              @timeout = arg
            when '--noverify'
              @verify = false
            when '--exact-matching'
              @exact = true
          end
        end

        if @use_chimpd && ( @script.nil? || @script.empty? )
          if @chimpd_wait_until_done == false
            puts "#######################################################"
            puts "ERROR: --script cannot be empty when sending to chimpd"
            puts "#######################################################"
            exit 1
          end
        end


      rescue GetoptLong::InvalidOption => ex
        help
        exit 1
      end

      #
      # Before we're totally done parsing command line options,
      # let's make sure that a few things make sense
      #
      if @group_concurrency > @concurrency
        @concurrency = @group_concurrency
      end
    end
942066
def run(self):
    
    self.parser = MultioptOptionParser(
      usage="%prog <command> [options] [args]",
      prog=self.clsname,
      version=self.version,
      option_list=self.global_options,
      description=self.desc_short,
      commands=self.command_set,
      epilog=self.footer
    )
    
    try:
      self.options, self.args = self.parser.parse_args(self.argv)    
    except Exception, e:
      print str(e)
      pass

    if len(self.args) < 1:
      self.parser.print_lax_help()
      return 2
    
    self.command = self.args.pop(0)
    showHelp = False
    
    if self.command == 'help': 
      if len(self.args) < 1:
        self.parser.print_lax_help()
        return 2
      else:
        self.command = self.args.pop()
        showHelp = True

    if self.command not in self.valid_commands:
      self.parser.print_cmd_error(self.command)
      return 2

    self.command_set[self.command].set_cmdname(self.command)
    subcmd_parser = self.command_set[self.command].get_parser(self.clsname, self.version, self.global_options)
    subcmd_options, subcmd_args = subcmd_parser.parse_args(self.args)

    if showHelp:
      subcmd_parser.print_help_long()
      return 1

    try:
      self.command_set[self.command].func(subcmd_options, *subcmd_args)
    except (CommandError, TypeError), e:
      # self.parser.print_exec_error(self.command, str(e))
      subcmd_parser.print_exec_error(self.command, str(e))
      print 
      # @TODO show command help
      # self.parser.print_lax_help()
      return 2

      
    return 1
825510
def main(argv=None, apply_config=True):
    """"""
    if argv is None:
        argv = sys.argv

    try:
        # Exit on broken pipe.
        signal.signal(signal.SIGPIPE, signal.SIG_DFL)
    except AttributeError:  # pragma: no cover
        # SIGPIPE is not available on Windows.
        pass

    try:
        args = parse_args(argv[1:], apply_config=apply_config)

        if args.list_fixes:
            for code, description in sorted(supported_fixes()):
                print('{code} - {description}'.format(
                    code=code, description=description))
            return 0

        if args.files == ['-']:
            assert not args.in_place

            encoding = sys.stdin.encoding or get_encoding()

            # LineEndingWrapper is unnecessary here due to the symmetry between
            # standard in and standard out.
            wrap_output(sys.stdout, encoding=encoding).write(
                fix_code(sys.stdin.read(), args, encoding=encoding))
        else:
            if args.in_place or args.diff:
                args.files = list(set(args.files))
            else:
                assert len(args.files) == 1
                assert not args.recursive

            fix_multiple_files(args.files, args, sys.stdout)
    except KeyboardInterrupt:
        return 1
184251
def main(argv=sys.argv[1:]):
    """"""

    global ext_lang

    parser = argparse.ArgumentParser(description=description,
                                     epilog=epilog)
    parser.add_argument('files', metavar='FILES', nargs='*',
                        help='the files to process')
    parser.add_argument('--version', action='version', version=version)
    parser.add_argument('-i', '--in-place', action='store_true',
                        help='modify files inplace')
    parser.add_argument('--print-langs', action='store_true',
                        help='print out all the supported languages')
    parser.add_argument('--lang', action='store', default='auto',
                        help='use the language with given extention')
    args = parser.parse_args(argv)

    # Print the current set of working languages.
    if args.print_langs:
        parser.print_usage()
        sys.stdout.write('\n')
        sys.stdout.write(textwrap.fill(textwrap.dedent("""\
        The following languages are supported:
        """)) + '\n')
        for cls in sorted({getattr(langs, nm) for nm in langs.__all__}):
            l = cls.__name__
            out = cls.__doc__.split('\n\n')[0]
            out = out + ' (' + ', '.join(cls.ext) + ')'

            prefix2 = ' '.join([''] * 20)
            prefix1 = prefix2[:2] + l + prefix2[2 + len(l):]

            wrapped = textwrap.fill(out, initial_indent=prefix1,
                                    subsequent_indent=prefix2)

            sys.stdout.write(wrapped + '\n')

        parser.exit(0)          # Exit once we're done

    if not args.files:
        parser.print_usage()

    for fname in args.files:
        # load the file
        with open(fname) as f:
            text = f.read()

        # generate the new output according to the language
        if args.lang == 'auto':
            l = language(fname)
        else:
            l = language(args.lang, True)
        text = l.gen(text)

        # emit the output
        if args.in_place:
            with open(fname, 'w') as f:
                f.write(text)
        else:
            sys.stdout.write(text)
182194
def parse_args():
  ''' 
  '''
  parser = optparse.OptionParser()

  parser.add_option("-v", "--verbose", action="store_true")

  mode_group = optparse.OptionGroup(parser, "Program Mode")
  mode_group.add_option("-u", "--update-status", action="store_const",
                        dest="mode", const="update_status")
  mode_group.add_option("-g", "--generate-cfg", action="store_const",
                        dest="mode", const="generate_cfg")
  parser.add_option_group(mode_group)
  parser.set_defaults(mode="update_status")

  general_options = optparse.OptionGroup(parser, "CM API Configuration")
  general_options.add_option("-H", "--host", metavar="HOST",
                             help="CM API hostname")
  general_options.add_option("-p", "--port", help="CM API port", default=None)
  general_options.add_option("-P", "--passfile", metavar="FILE",
                             help="File containing CM API username and password, "
                                  "colon-delimited on a single line.  E.g. "
                                  "\"user:pass\"")
  general_options.add_option("--use-tls", action="store_true",
                             help="Use TLS", default=False)
  parser.add_option_group(general_options)

  polling_options = optparse.OptionGroup(parser, "Status Update Options")
  polling_options.add_option("-c", "--cmd-file", metavar="FILE",
                             help="Path to the file that Nagios checks for "
                                  "external command requests.")
  polling_options.add_option("-n", "--use-send-nsca", action="store_true",
                             default=False,
                             help="Use send_nsca to report status via a nsca "
                                  "daemon. When using this option, the "
                                  "send_nsca program must be available and the "
                                  "nsca daemon host and port must be provided."
                                  "Default is false.")
  polling_options.add_option("--send-nsca-path", metavar="PATH",
                             default="/usr/sbin/send_nsca",
                             help="Path to send_nsca, default is "
                                  "/usr/sbin/send_nsca")
  polling_options.add_option("--nsca-host", metavar="HOST",
                             default="localhost",
                             help="When using send_nsca, the hostname of NSCA "
                                  "server, default is localhost.")
  polling_options.add_option("--nsca-port", metavar="PORT", default=None,
                             help="When using send_nsca, the port on which the "
                                  "server is running, default is 5667.")
  polling_options.add_option("--send-nsca-config", metavar="FILE", default=None,
                             help="Config file passed to send_nsca -c. Default"
                                  " is to not specify the config parameter.")
  parser.add_option_group(polling_options)


  generate_options = optparse.OptionGroup(parser, "Generate Config Options")
  generate_options.add_option("--cfg-dir", metavar="DIR", default=getcwd(),
                              help="Directory for generated Nagios cfg files.")
  parser.add_option_group(generate_options)

  (options, args) = parser.parse_args()

  ''' Parse the 'passfile' - it must contain the username and password,
      colon-delimited on a single line. E.g.:
      $ cat ~/protected/cm_pass
      admin:admin
  '''
  required = ["host", "passfile"]

  if options.mode == "update_status":
    if not options.use_send_nsca:
      required.append("cmd_file")

  for required_opt in required:
    if getattr(options, required_opt) is None:
      parser.error("Please specify the required argument: --%s" %
                   (required_opt.replace('_','-'),))

  return (options, args)
4676
def main(args=None):
    
    parser = ArgumentParser(usage=__usage__)
    parser.add_argument("--no-skip-hidden", action="store_false",
                        dest="skip_hidden",
                        help="Do not skip hidden files. "
                        "Use this if you know what you are doing...")
    parser.add_argument("--include", dest="includes", action="append",
                        help="Only replace in files matching theses patterns")
    parser.add_argument("--exclude", dest="excludes", action="append",
                        help="Ignore files matching theses patterns")
    parser.add_argument("--backup",
                        action="store_true", dest="backup",
                        help="Create a backup for each file. "
                             "By default, files are modified in place")
    parser.add_argument("--go",
                        action="store_true", dest="go",
                        help="Perform changes rather than just printing then")
    parser.add_argument("--dry-run", "-n",
                        action="store_false", dest="go",
                        help="Do not change anything. This is the default")
    parser.add_argument("--color", choices=["always", "never", "auto"],
                        help="When to colorize the output. "
                             "Default: when output is a tty")
    parser.add_argument("--no-color", action="store_false", dest="color",
                        help="Do not colorize output")
    parser.add_argument("--quiet", "-q", action="store_true", dest="quiet",
                        help="Do not produce any output")
    parser.add_argument("pattern")
    parser.add_argument("replacement")
    parser.add_argument("paths", nargs="*")

    parser.set_defaults(
        includes=list(),
        excludes=list(),
        skip_hidden=True,
        backup=False,
        go=False,
        color="auto",
        quiet=False,
        )

    args = parser.parse_args(args=args)
    setup_colors(args)
    repl_main(args)
17553
def parse(cmdline = ARGV)
			vals = {}
			required = {}

			opt :version, "Print version and exit" if @version && ! (@specs[:version] || @long["version"])
			opt :help, "Show this message" unless @specs[:help] || @long["help"]

			@specs.each do |sym, opts|
				required[sym] = true if opts.required?
				vals[sym] = opts.default
				vals[sym] = [] if opts.multi && !opts.default # multi arguments default to [], not nil
			end

			resolve_default_short_options!

			## resolve symbols
			given_args = {}
			@leftovers = each_arg cmdline do |arg, params|
				## handle --no- forms
				arg, negative_given = if arg =~ /^--no-([^-]\S*)$/
																["--#{$1}", true]
															else
																[arg, false]
															end

				sym = case arg
							when /^-([^-])$/      then @short[$1]
							when /^--([^-]\S*)$/  then @long[$1] || @long["no-#{$1}"]
							else                       raise CommandlineError, "invalid argument syntax: '#{arg}'"
							end

				sym = nil if arg =~ /--no-/ # explicitly invalidate --no-no- arguments

				next nil if ignore_invalid_options && !sym
				raise CommandlineError, "unknown argument '#{arg}'" unless sym

				if given_args.include?(sym) && !@specs[sym].multi?
					raise CommandlineError, "option '#{arg}' specified multiple times"
				end

				given_args[sym] ||= {}
				given_args[sym][:arg] = arg
				given_args[sym][:negative_given] = negative_given
				given_args[sym][:params] ||= []

				# The block returns the number of parameters taken.
				num_params_taken = 0

				unless params.empty?
					if @specs[sym].single_arg?
						given_args[sym][:params] << params[0, 1]  # take the first parameter
						num_params_taken = 1
					elsif @specs[sym].multi_arg?
						given_args[sym][:params] << params        # take all the parameters
						num_params_taken = params.size
					end
				end

				num_params_taken
			end

			## check for version and help args
			raise VersionNeeded if given_args.include? :version
			raise HelpNeeded if given_args.include? :help

			## check constraint satisfaction
			@constraints.each do |type, syms|
				constraint_sym = syms.find { |sym| given_args[sym] }
				next unless constraint_sym

				case type
				when :depends
					syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} requires --#{@specs[sym].long}" unless given_args.include? sym }
				when :conflicts
					syms.each { |sym| raise CommandlineError, "--#{@specs[constraint_sym].long} conflicts with --#{@specs[sym].long}" if given_args.include?(sym) && (sym != constraint_sym) }
				end
			end

			required.each do |sym, val|
				raise CommandlineError, "option --#{@specs[sym].long} must be specified" unless given_args.include? sym
			end

			## parse parameters
			given_args.each do |sym, given_data|
				arg, params, negative_given = given_data.values_at :arg, :params, :negative_given

				opts = @specs[sym]
				if params.empty? && !opts.flag?
					raise CommandlineError, "option '#{arg}' needs a parameter" unless opts.default
					params << (opts.array_default? ? opts.default.clone : [opts.default])
				end

				params[0].each do |p|
					raise CommandlineError, "option '#{arg}' only accepts one of: #{opts.permitted.join(', ')}" unless opts.permitted.include? p
				end unless opts.permitted.nil?

				vals["#{sym}_given".intern] = true # mark argument as specified on the commandline

				vals[sym] = opts.parse(params, negative_given)

				if opts.single_arg?
					if opts.multi?        # multiple options, each with a single parameter
						vals[sym] = vals[sym].map { |p| p[0] }
					else                  # single parameter
						vals[sym] = vals[sym][0][0]
					end
				elsif opts.multi_arg? && !opts.multi?
					vals[sym] = vals[sym][0]  # single option, with multiple parameters
				end
				# else: multiple options, with multiple parameters

				opts.callback.call(vals[sym]) if opts.callback
			end

			## modify input in place with only those
			## arguments we didn't process
			cmdline.clear
			@leftovers.each { |l| cmdline << l }

			## allow openstruct-style accessors
			class << vals
				def method_missing(m, *_args)
					self[m] || self[m.to_s]
				end
			end
			vals
		end
309
def main(args=None):
    """"""
    parser = _parser()

    # Python 2 will error 'too few arguments' if no subcommand is supplied.
    # No such error occurs in Python 3, which makes it feasible to check
    # whether a subcommand was provided (displaying a help message if not).
    # argparse internals vary significantly over the major versions, so it's
    # much easier to just override the args passed to it. In this case, print
    # the usage message if there are no args.
    if args is None and len(sys.argv) <= 1:
        sys.argv.append('--help')

    options = parser.parse_args(args)

    # pass options to subcommand
    options.func(options)

    return 0