Parse command line arguments
545945
def parse_known_args():
    
    parser = ArgumentParser()
    parser.add_argument("-l", "--loop", type=int, help="Loop every X seconds")
    parser.add_argument('-V', '--version',
                        action='store_true',
                        dest='version',
                        help='Print the version number and exit')
    parser.add_argument("-u", "--update",
                        action='store_true',
                        dest="update",
                        help="Update the software from online repo")
    parser.add_argument("-p", "--problem",
                        action='store_true',
                        dest="problem",
                        help="Report a problem")
    parser.add_argument("-m", "--memory",
                        action='store_true',
                        dest="memory",
                        help="Run memory tests")
    args, otherthings = parser.parse_known_args()
    return args, otherthings, parser
1286547
def parse_args(args=None):
    """"""
    parser = argparse.ArgumentParser(description='afraid.org dyndns client')

    ## positional arguments

    parser.add_argument('user')
    parser.add_argument('password')
    parser.add_argument('hosts',
            nargs='*',
            help='(deafult: all associated hosts)',
            default=None
    )

    ## optional arguments

    # should we fork?
    parser.add_argument('--daemonize', '-d',
        action='store_true',
        default=False,
        help='run in background (default: no)',
    )

    # log to a file or stdout
    parser.add_argument('--log',
        help='log to file (default: log to stdout)',
        type=argparse.FileType('w'),
        default=sys.stdout,
        metavar='file'
    )

    # how long to sleep between updates
    parser.add_argument('--interval',
        help='update interval, in seconds (default: 21600)',
        metavar='seconds',
        default=6 * 60 * 60, # 6 hours
        type=int
    )

    return parser.parse_args(args)
1187805
def _parse_args(self, args=None, values=None):
        """"""
        options, arguments = self._parser.parse_args(args, values)
        return self._fix_set_options(options), arguments
1309159
private function parseArgs() {
        // Use the global $argv variable to retrieve command-line arguments
        global $argv;

        // Reset values
        $this->_flags       = [];
        $this->_options     = [];
        $this->_parameters  = [];

        // index[0] is the script name and index[1] is the command name
        // so count starts from 2 from now on
        for ($i = 2; $i < count($argv); $i++) {
            if (strpos($argv[$i], '-') === 0) {
                // In gnuopt flags are determined by parameters that starts with `-`
                $flag = ltrim($argv[$i], '-');
                // Make sure that every things splittable
                $flag = strlen($flag) > 1 ? str_split($flag) : [$flag];
                // Then register flags
                $this->_flags = array_merge($this->_flags, $flag);
            } else if (strpos($argv[$i], $this->_delimeter) > 0) {
                // In our history options are the parameters that lets the user
                // to set the value of a key 
                $tokens = explode($this->_delimeter, $argv[$i]);
                // Make sure to remove the option key
                $param_name = strtolower($tokens[0]);
                array_shift($tokens);
                // Then let the others to be the value
                $param_value = implode($this->_delimeter, $tokens);
                // Register options
                // NOTE: Options are allowed to be overwritten
                $this->_options[$param_name] = $param_value;
            } else {
                // Else, it a parameter
                $this->_parameters[] = $argv[$i];
            }
        }
    }
1076400
def parse_args(arguments, apply_config=False):
    """"""
    parser = create_parser()
    args = parser.parse_args(arguments)

    if not args.files and not args.list_fixes:
        parser.error('incorrect number of arguments')

    args.files = [decode_filename(name) for name in args.files]

    if apply_config:
        parser = read_config(args, parser)
        args = parser.parse_args(arguments)
        args.files = [decode_filename(name) for name in args.files]

    if '-' in args.files:
        if len(args.files) > 1:
            parser.error('cannot mix stdin and regular files')

        if args.diff:
            parser.error('--diff cannot be used with standard input')

        if args.in_place:
            parser.error('--in-place cannot be used with standard input')

        if args.recursive:
            parser.error('--recursive cannot be used with standard input')

    if len(args.files) > 1 and not (args.in_place or args.diff):
        parser.error('autopep8 only takes one filename as argument '
                     'unless the "--in-place" or "--diff" args are '
                     'used')

    if args.recursive and not (args.in_place or args.diff):
        parser.error('--recursive must be used with --in-place or --diff')

    if args.in_place and args.diff:
        parser.error('--in-place and --diff are mutually exclusive')

    if args.max_line_length <= 0:
        parser.error('--max-line-length must be greater than 0')

    if args.select:
        args.select = _split_comma_separated(args.select)

    if args.ignore:
        args.ignore = _split_comma_separated(args.ignore)
        if not all(
                any(
                    conflicting_code.startswith(ignore_code)
                    for ignore_code in args.ignore
                )
                for conflicting_code in CONFLICTING_CODES
        ):
            args.ignore.update(CONFLICTING_CODES)
    elif not args.select:
        if args.aggressive:
            # Enable everything by default if aggressive.
            args.select = {'E', 'W1', 'W2', 'W3', 'W6'}
        else:
            args.ignore = _split_comma_separated(DEFAULT_IGNORE)

    if args.exclude:
        args.exclude = _split_comma_separated(args.exclude)
    else:
        args.exclude = {}

    if args.jobs < 1:
        # Do not import multiprocessing globally in case it is not supported
        # on the platform.
        import multiprocessing
        args.jobs = multiprocessing.cpu_count()

    if args.jobs > 1 and not args.in_place:
        parser.error('parallel jobs requires --in-place')

    if args.line_range:
        if args.line_range[0] <= 0:
            parser.error('--range must be positive numbers')
        if args.line_range[0] > args.line_range[1]:
            parser.error('First value of --range should be less than or equal '
                         'to the second')

    return args
1281947
def parse_cli_args():
    
    # get config paths
    home_path = os.path.expanduser("~")
    xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path))
    xdg_dirs_path = os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg")

    # get i3status path
    try:
        with open(os.devnull, "w") as devnull:
            command = ["which", "i3status"]
            i3status_path = (
                subprocess.check_output(command, stderr=devnull).decode().strip()
            )
    except subprocess.CalledProcessError:
        i3status_path = None

    # get window manager
    with open(os.devnull, "w") as devnull:
        if subprocess.call(["pgrep", "i3"], stdout=devnull) == 0:
            wm = "i3"
        else:
            wm = "sway"

    # i3status config file default detection
    # respect i3status' file detection order wrt issue #43
    i3status_config_file_candidates = [
        "{}/py3status/config".format(xdg_home_path),
        "{}/i3status/config".format(xdg_home_path),
        "{}/i3/i3status.conf".format(xdg_home_path),  # custom
        "{}/.i3status.conf".format(home_path),
        "{}/.i3/i3status.conf".format(home_path),  # custom
        "{}/i3status/config".format(xdg_dirs_path),
        "/etc/i3status.conf",
    ]
    for fn in i3status_config_file_candidates:
        if os.path.isfile(fn):
            i3status_config_file_default = fn
            break
    else:
        # if files does not exists, defaults to ~/.i3/i3status.conf
        i3status_config_file_default = i3status_config_file_candidates[3]

    class Parser(argparse.ArgumentParser):
        # print usages and exit on errors
        def error(self, message):
            print("\x1b[1;31merror: \x1b[0m{}".format(message))
            self.print_help()
            self.exit(1)

        # hide choices on errors
        def _check_value(self, action, value):
            if action.choices is not None and value not in action.choices:
                raise argparse.ArgumentError(
                    action, "invalid choice: '{}'".format(value)
                )

    class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
        def _format_action_invocation(self, action):
            metavar = self._format_args(action, action.dest.upper())
            return "{} {}".format(", ".join(action.option_strings), metavar)

    # command line options
    parser = Parser(
        description="The agile, python-powered, i3status wrapper",
        formatter_class=HelpFormatter,
    )
    parser.add_argument(
        "-b",
        "--dbus-notify",
        action="store_true",
        dest="dbus_notify",
        help="send notifications via dbus instead of i3-nagbar",
    )
    parser.add_argument(
        "-c",
        "--config",
        action="store",
        default=i3status_config_file_default,
        dest="i3status_config_path",
        help="load config",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_true",
        help="enable debug logging in syslog and --log-file",
    )
    parser.add_argument(
        "-g",
        "--gevent",
        action="store_true",
        dest="gevent",
        help="enable gevent monkey patching",
    )
    parser.add_argument(
        "-i",
        "--include",
        action="append",
        dest="include_paths",
        help="append additional user-defined module paths",
        metavar="PATH",
    )
    parser.add_argument(
        "-l",
        "--log-file",
        action="store",
        dest="log_file",
        help="enable logging to FILE",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-s",
        "--standalone",
        action="store_true",
        dest="standalone",
        help="run py3status without i3status",
    )
    parser.add_argument(
        "-t",
        "--timeout",
        action="store",
        default=60,
        dest="cache_timeout",
        help="default module cache timeout in seconds",
        metavar="INT",
        type=int,
    )
    parser.add_argument(
        "-m",
        "--disable-click-events",
        action="store_true",
        dest="disable_click_events",
        help="disable all click events",
    )
    parser.add_argument(
        "-u",
        "--i3status",
        action="store",
        default=i3status_path,
        dest="i3status_path",
        help="specify i3status path",
        metavar="PATH",
        type=str,
    )
    parser.add_argument(
        "-v",
        "--version",
        action="store_true",
        dest="print_version",
        help="show py3status version and exit",
    )
    parser.add_argument(
        "--wm",
        action="store",  # add comment to preserve formatting
        dest="wm",
        metavar="WINDOW_MANAGER",
        default=wm,
        choices=["i3", "sway"],
        help="specify window manager i3 or sway",
    )

    # deprecations
    parser.add_argument("-n", "--interval", help=argparse.SUPPRESS)

    # parse options, command, etc
    options = parser.parse_args()

    # make versions
    options.python_version = python_version()
    options.version = version
    if options.print_version:
        msg = "py3status version {version} (python {python_version}) on {wm}"
        print(msg.format(**vars(options)))
        parser.exit()

    # get wm
    options.wm_name = options.wm
    options.wm = {
        "i3": {"msg": "i3-msg", "nag": "i3-nagbar"},
        "sway": {"msg": "swaymsg", "nag": "swaynag"},
    }[options.wm]

    # make it i3status if None
    if not options.i3status_path:
        options.i3status_path = "i3status"

    # make include path to search for user modules if None
    if not options.include_paths:
        options.include_paths = [
            "{}/py3status/modules".format(xdg_home_path),
            "{}/i3status/py3status".format(xdg_home_path),
            "{}/i3/py3status".format(xdg_home_path),
            "{}/.i3/py3status".format(home_path),
        ]

    include_paths = []
    for path in options.include_paths:
        path = os.path.abspath(path)
        if os.path.isdir(path) and os.listdir(path):
            include_paths.append(path)
    options.include_paths = include_paths

    # defaults
    del options.interval
    del options.print_version
    options.minimum_interval = 0.1  # minimum module update interval
    options.click_events = not options.__dict__.pop("disable_click_events")

    # all done
    return options
1327387
def parse_arguments():
    """"""

    parser = argparse.ArgumentParser(prog=sys.argv[0],
                                     description='Send Webhooks Channel events to IFTTT',
                                     epilog='Visit https://ifttt.com/channels/maker_webhooks for more information')
    parser.add_argument('--version', action='version', version=pyfttt.__version__)

    sgroup = parser.add_argument_group(title='sending events')
    sgroup.add_argument('-k', '--key', metavar='K',
                        default=os.environ.get('IFTTT_API_KEY'),
                        help='IFTTT secret key')
    sgroup.add_argument('-e', '--event', metavar='E', required=True,
                        help='The name of the event to trigger')
    sgroup.add_argument('value1', nargs='?',
                        help='Extra data sent with the event (optional)')
    sgroup.add_argument('value2', nargs='?',
                        help='Extra data sent with the event (optional)')
    sgroup.add_argument('value3', nargs='?',
                        help='Extra data sent with the event (optional)')

    return parser.parse_args()
33666
private CommandLine parseArgs(String[] args) throws ParseException {
        final CommandLineParser parser = new DefaultParser();
        final Options options = createCommandLineOptions();
        return parser.parse(options, args);
    }
551356
def parse_args():
    
    parser = ArgumentParser(description="PyTorch distributed training launch "
                                        "helper utilty that will spawn up "
                                        "multiple distributed processes")

    # Optional arguments for the launch helper
    parser.add_argument("--nnodes", type=int, default=1,
                        help="The number of nodes to use for distributed "
                             "training")
    parser.add_argument("--node_rank", type=int, default=0,
                        help="The rank of the node for multi-node distributed "
                             "training")
    parser.add_argument("--nproc_per_node", type=int, default=1,
                        help="The number of processes to launch on each node, "
                             "for GPU training, this is recommended to be set "
                             "to the number of GPUs in your system so that "
                             "each process can be bound to a single GPU.")
    parser.add_argument("--master_addr", default="127.0.0.1", type=str,
                        help="Master node (rank 0)'s address, should be either "
                             "the IP address or the hostname of node 0, for "
                             "single node multi-proc training, the "
                             "--master_addr can simply be 127.0.0.1")
    parser.add_argument("--master_port", default=29500, type=int,
                        help="Master node (rank 0)'s free port that needs to "
                             "be used for communciation during distributed "
                             "training")
    parser.add_argument('--no_hyperthreads', action='store_true',
                        help='Flag to disable binding to hyperthreads')
    parser.add_argument('--no_membind', action='store_true',
                        help='Flag to disable memory binding')

    # non-optional arguments for binding
    parser.add_argument("--nsockets_per_node", type=int, required=True,
                        help="Number of CPU sockets on a node")
    parser.add_argument("--ncores_per_socket", type=int, required=True,
                        help="Number of CPU cores per socket")

    # positional
    parser.add_argument("training_script", type=str,
                        help="The full path to the single GPU training "
                             "program/script to be launched in parallel, "
                             "followed by all the arguments for the "
                             "training script")

    # rest from the training program
    parser.add_argument('training_script_args', nargs=REMAINDER)
    return parser.parse_args()
598412
def parse_args():
    
    parser = argparse.ArgumentParser(description="Decrypt YubiKey OTPs using YubiHSM",
                                     add_help=True,
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter
                                     )
    parser.add_argument('-D', '--device',
                        dest='device',
                        default=default_device,
                        required=False,
                        help='YubiHSM device'
                        )
    parser.add_argument('-B', '--aead-dir',
                        dest='aead_dir',
                        default=default_dir,
                        required=False,
                        help='AEAD directory - base directory of your AEADs',
                        metavar='DIR',
                        )
    parser.add_argument('-U', '--serve-url',
                        dest='serve_url',
                        default=default_serve_url,
                        required=False,
                        help='Base URL for decrypt web service',
                        metavar='URL',
                        )
    parser.add_argument('-S', '--stats-url',
                        dest='stats_url',
                        required=False,
                        help='URL where statistics can be retrieved',
                        metavar='URL',
                        )
    parser.add_argument('-v', '--verbose',
                        dest='verbose',
                        action='store_true', default=False,
                        help='Enable verbose operation'
                        )
    parser.add_argument('-d', '--daemon',
                        dest='daemon',
                        action='store_true', default=False,
                        help='Run as daemon'
                        )
    parser.add_argument('--debug',
                        dest='debug',
                        action='store_true', default=False,
                        help='Enable debug operation'
                        )
    parser.add_argument('--port',
                        dest='listen_port',
                        type=int, default=default_port,
                        required=False,
                        help='Port to listen on',
                        metavar='PORT',
                        )
    parser.add_argument('--addr',
                        dest='listen_addr',
                        default=default_listen_addr,
                        required=False,
                        help='Address to bind to',
                        metavar='ADDR',
                        )
    parser.add_argument('--reqtimeout',
                        dest='reqtimeout',
                        type=int, default=default_reqtimeout,
                        required=False,
                        help='Request timeout in seconds',
                        metavar='SECONDS',
                        )
    parser.add_argument('--key-handle', '--key-handles',
                        dest='key_handles',
                        nargs='+',
                        required=True,
                        help='Key handle(s) to use to decrypt AEADs on the YHSM.',
                        metavar='HANDLE',
                        )
    parser.add_argument('--pid-file',
                        dest='pid_file',
                        default=default_pid_file,
                        required=False,
                        help='PID file',
                        metavar='FILENAME',
                        )
    parser.add_argument('--db-url',
                        dest='db_url',
                        default=default_db_url,
                        required=False,
                        help='The database url to read the AEADs from, you can '
                        'also use env:YOURENVVAR to instead read the URL from '
                        'the YOURENVVAR environment variable.',
                        metavar='DBURL',
                        )
    parser.add_argument('--proxy', '--proxies',
                        dest='proxies',
                        nargs='+',
                        required=False,
                        default=[],
                        help='IP addresses of proxies where the IP in '
                        'X-Forwarded-For should be used for logging purposes.',
                        metavar='IP',
                        )

    return parser.parse_args()
380275
def parse_arguments(argv):
    

    parser = argparse.ArgumentParser(description="GNS3 server version {}".format(__version__))
    parser.add_argument("-v", "--version", help="show the version", action="version", version=__version__)
    parser.add_argument("--host", help="run on the given host/IP address")
    parser.add_argument("--port", help="run on the given port", type=int)
    parser.add_argument("--ssl", action="store_true", help="run in SSL mode")
    parser.add_argument("--no-ubridge", action="store_false", help="do not use ubridge to handle node connections")
    parser.add_argument("--config", help="Configuration file")
    parser.add_argument("--certfile", help="SSL cert file")
    parser.add_argument("--certkey", help="SSL key file")
    parser.add_argument("--record", help="save curl requests into a file (for developers)")
    parser.add_argument("-L", "--local", action="store_true", help="local mode (allows some insecure operations)")
    parser.add_argument("-A", "--allow", action="store_true", help="allow remote connections to local console ports")
    parser.add_argument("-q", "--quiet", action="store_true", help="do not show logs on stdout")
    parser.add_argument("-d", "--debug", action="store_true", help="show debug logs")
    parser.add_argument("--shell", action="store_true", help="start a shell inside the server (debugging purpose only you need to install ptpython before)")
    parser.add_argument("--log", help="send output to logfile instead of console")
    parser.add_argument("--daemon", action="store_true", help="start as a daemon")
    parser.add_argument("--pid", help="store process pid")
    parser.add_argument("--profile", help="Settings profile (blank will use default settings files)")

    args = parser.parse_args(argv)
    if args.config:
        Config.instance(files=[args.config], profile=args.profile)
    else:
        Config.instance(profile=args.profile)

    config = Config.instance().get_section_config("Server")
    defaults = {
        "host": config.get("host", "0.0.0.0"),
        "port": config.get("port", 3080),
        "ssl": config.getboolean("ssl", False),
        "certfile": config.get("certfile", ""),
        "certkey": config.get("certkey", ""),
        "record": config.get("record", ""),
        "local": config.getboolean("local", False),
        "allow": config.getboolean("allow_remote_console", False),
        "quiet": config.getboolean("quiet", False),
        "debug": config.getboolean("debug", False),
        "logfile": config.getboolean("logfile", "")
    }

    parser.set_defaults(**defaults)
    return parser.parse_args(argv)
227626
def parse_args(args):
    
    index = None
    for arg_i, arg in enumerate(args):
        if not arg.startswith('-'):
            index = arg_i
            break

    # Unable to parse any arguments
    if index is None:
        return (args, None, [])

    return (args[:index], args[index], args[(index + 1):])
920723
def parseargs(argv):
    ''''''
    args = []
    options = {}
    key = None
    for arg in argv:
        if arg in DEFAULT_OPTION_VALUES:
            key = arg.strip('=').replace('-', '_')
            options[key] = ()
        elif key is None:
            args.append(arg)
        else:
            options[key] += (arg,)

    if set(args) & {'-h', '--help'}:
        print(__doc__, end='')
        exit(0)
    elif set(args) & {'-V', '--version'}:
        print(__version__)
        exit(0)
    elif args:
        exit('invalid option: %s\nTry --help for more information.' % args[0])

    return options
830393
def parse_command_line_arguments(argparse_parser, init_indent=5, subs_indent=5,
                                 line_width=76):
    """"""
    # Redirect stdout and stderr to prettify help or usage output from argparse.
    old_stdout = sys.stdout # save stdout
    old_stderr = sys.stderr # save stderr
    sys.stdout = RedirectHelp(sys.stdout, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stdout to add postprocessor
    sys.stderr = RedirectHelp(sys.stderr, help_string_replacement_pairs,
            init_indent, subs_indent, line_width) # redirect stderr to add postprocessor

    # Run the actual argument-parsing operation via argparse.
    args = argparse_parser.parse_args()

    # The argparse class has finished its argument-processing, so now no more
    # usage or help messages will be printed.  So restore stdout and stderr
    # to their usual settings, except with self-flushing added.
    sys.stdout = SelfFlushingOutstream(old_stdout)
    sys.stderr = SelfFlushingOutstream(old_stderr)

    return args
945141
def _get_args_to_parse(args, sys_argv):
    
    arguments = args if args is not None else sys_argv[1:]
    _LOG.debug("Parsing arguments: %s", arguments)
    return arguments
1047173
def parse_args():
    '''  '''

    parser = argparse.ArgumentParser(prog='setup_tree_modules', usage='%(prog)s [opts]')
    parser.add_argument('-v', '--verbose', action='store_true', dest='verbose',
                        help='Print extra information.', default=False)
    parser.add_argument('-r', '--root', action='store', dest='root', default=os.getenv('SAS_BASE_DIR'),
                        help='Override the value of $SAS_BASE_DIR.', metavar='SAS_BASE_DIR')
    parser.add_argument('-t', '--treedir', action='store', dest='treedir', default=os.getenv('TREE_DIR'),
                        help='Override the value of $TREE_DIR.', metavar='TREE_DIR')
    parser.add_argument('-m', '--modulesdir', action='store', dest='modulesdir', default=os.getenv('MODULES_DIR'),
                        help='Your modules directory', metavar='MODULES_DIR')
    parser.add_argument('-e', '--env', action='store_true', dest='env',
                        help='Create tree environment symlinks.', default=False)
    parser.add_argument('-i', '--mirror', action='store_true', dest='mirror',
                        help='Use the mirror site (SAM) instead.')
    parser.add_argument('-o', '--only', action='store', dest='only', metavar='[xxx].cfg',
                        default=None, help='create links for only the specified tree config.')

    opts = parser.parse_args()

    return opts
159567
def parse_command_line():
    """"""
    parser = argparse.ArgumentParser(
        prog='csp_pulsar_sender',
        description='Send fake pulsar data using ftp protocol.')
    parser.add_argument('config_file', type=argparse.FileType('r'),
                        help='JSON configuration file.')
    parser.add_argument('-v', '--verbose', help='Enable verbose messages.',
                        action='store_true')
    parser.add_argument('-p', '--print_settings', help='Print settings file.',
                        action='store_true')
    return parser.parse_args()