Parse argv of terminal

        :param argv: default is sys.argv
964495
def parse(self, argv=None):
        

        if not argv:
            argv = sys.argv
        elif isinstance(argv, str):
            argv = argv.split()

        self._argv = argv[1:]
        if not self._argv:
            self.validate_options()
            if self._command_func:
                self._command_func(**self._results)
                return True
            return False

        cmd = self._argv[0]

        if not cmd.startswith('-'):
            # parse subcommands
            for command in self._command_list:
                if isinstance(command, Command) and command._name == cmd:
                    command._parent = self
                    return command.parse(self._argv)

        _positional_index = 0
        while self._argv:
            arg = self._argv[0]
            self._argv = self._argv[1:]
            if not self.parse_options(arg):
                self._args_results.append(arg)
                if len(self._positional_list) > _positional_index:
                    # positional arguments
                    key = self._positional_list[_positional_index]
                    self._results[key] = arg
                    _positional_index += 1

        # validate
        self.validate_options()

        if self._parent and isinstance(self._parent, Command):
            self._parent._args_results = self._args_results

        if self._command_func:
            self._command_func(**self._results)
            return True
        return False
745571
def _run_argparser(self, argv):
        
        if self._parser is None:
            raise ValueError('Link was not given a parser on initialization')
        args = self._parser.parse_args(argv)
        self.update_args(args.__dict__)
        return args
1117121
def parse_args():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument("font_path", help="Path to ttf font file or directory containing ttf files")
    parser.add_argument("--loss", help="'ctc' or 'warpctc' loss [Default 'ctc']", default='ctc')
    parser.add_argument("--cpu",
                        help="Number of CPUs for training [Default 8]. Ignored if --gpu is specified.",
                        type=int, default=8)
    parser.add_argument("--gpu", help="Number of GPUs for training [Default 0]", type=int)
    parser.add_argument("--num_proc", help="Number CAPTCHA generating processes [Default 4]", type=int, default=4)
    parser.add_argument("--prefix", help="Checkpoint prefix [Default 'ocr']", default='ocr')
    return parser.parse_args()
114901
def main(argv=None):
    
    if not argv:
        argv = sys.argv[1:]
    try:
        global COMMAND_LINE_FLAG
        COMMAND_LINE_FLAG = True
        parser = argparse.ArgumentParser(description=_HELP_TEXT)
        parser.add_argument('command', nargs='?', default=None,
                            help="One of 'ls', 'rm', 'put' or 'get'.")
        parser.add_argument('path', nargs='?', default=None,
                            help="Use when a file needs referencing.")
        parser.add_argument('target', nargs='?', default=None,
                            help="Use to specify a target filename.")
        args = parser.parse_args(argv)
        if args.command == 'ls':
            list_of_files = ls()
            if list_of_files:
                print(' '.join(list_of_files))
        elif args.command == 'rm':
            if args.path:
                rm(args.path)
            else:
                print('rm: missing filename. (e.g. "ufs rm foo.txt")')
        elif args.command == 'put':
            if args.path:
                put(args.path, args.target)
            else:
                print('put: missing filename. (e.g. "ufs put foo.txt")')
        elif args.command == 'get':
            if args.path:
                get(args.path, args.target)
            else:
                print('get: missing filename. (e.g. "ufs get foo.txt")')
        else:
            # Display some help.
            parser.print_help()
    except Exception as ex:
        # The exception of no return. Print exception information.
        print(ex)
557925
def run_from_argv(self, argv):
        
        if (len(argv) > 2 and not argv[2].startswith('-') and
                argv[2] in self.subcommands.keys()):
            subcommand = argv[2]
            klass = self.get_subcommand(subcommand)
            parser = OptionParser(
                prog=argv[0],
                usage=klass.usage('{0} {1}'.format(argv[1], subcommand)),
                version=klass.get_version(), option_list=klass.option_list)
            options, args = parser.parse_args(argv[3:])
            args = [subcommand] + args
        else:
            parser = self.create_parser(argv[0], argv[1])
            options, args = parser.parse_args(argv[2:])

        handle_default_options(options)
        self.execute(*args, **options.__dict__)
1203706
protected function _parseArg($argv) {
        for ($i = 0; $i < count($argv); $i++) {
            if ($argv[$i] != 'console') {
                if (!preg_match('#\[#', $argv[$i])) {
                    array_push($this->_argv, $argv[$i]);
                }
                else {
                    $data = '';

                    for ($i = 0; $i < count($argv); $i++) {
                        $data .= $argv[$i] . ' ';

                        if (preg_match('#\]#', $argv[$i])) {
                            $data = str_replace(['[', ']'], ['', ''], $data);
                            array_push($this->_argv, trim($data));
                            break;
                        }
                    }
                }
            }
        }
    }
968423
def _parse_arguments(args=None):
    
    parser = argparse.ArgumentParser(
        description='Pure python ssh tunnel utils\n'
                    'Version {0}'.format(__version__),
        formatter_class=argparse.RawTextHelpFormatter
    )

    parser.add_argument(
        'ssh_address',
        type=str,
        help='SSH server IP address (GW for SSH tunnels)\n'
             'set with "-- ssh_address" if immediately after '
             '-R or -L'
    )

    parser.add_argument(
        '-U', '--username',
        type=str,
        dest='ssh_username',
        help='SSH server account username'
    )

    parser.add_argument(
        '-p', '--server_port',
        type=int,
        dest='ssh_port',
        default=22,
        help='SSH server TCP port (default: 22)'
    )

    parser.add_argument(
        '-P', '--password',
        type=str,
        dest='ssh_password',
        help='SSH server account password'
    )

    parser.add_argument(
        '-R', '--remote_bind_address',
        type=_bindlist,
        nargs='+',
        default=[],
        metavar='IP:PORT',
        required=True,
        dest='remote_bind_addresses',
        help='Remote bind address sequence: '
             'ip_1:port_1 ip_2:port_2 ... ip_n:port_n\n'
             'Equivalent to ssh -Lxxxx:IP_ADDRESS:PORT\n'
             'If port is omitted, defaults to 22.\n'
             'Example: -R 10.10.10.10: 10.10.10.10:5900'
    )

    parser.add_argument(
        '-L', '--local_bind_address',
        type=_bindlist,
        nargs='*',
        dest='local_bind_addresses',
        metavar='IP:PORT',
        help='Local bind address sequence: '
             'ip_1:port_1 ip_2:port_2 ... ip_n:port_n\n'
             'Elements may also be valid UNIX socket domains: \n'
             '/tmp/foo.sock /tmp/bar.sock ... /tmp/baz.sock\n'
             'Equivalent to ssh -LPORT:xxxxxxxxx:xxxx, '
             'being the local IP address optional.\n'
             'By default it will listen in all interfaces '
             '(0.0.0.0) and choose a random port.\n'
             'Example: -L :40000'
    )

    parser.add_argument(
        '-k', '--ssh_host_key',
        type=str,
        help="Gateway's host key"
    )

    parser.add_argument(
        '-K', '--private_key_file',
        dest='ssh_private_key',
        metavar='KEY_FILE',
        type=str,
        help='RSA/DSS/ECDSA private key file'
    )

    parser.add_argument(
        '-S', '--private_key_password',
        dest='ssh_private_key_password',
        metavar='KEY_PASSWORD',
        type=str,
        help='RSA/DSS/ECDSA private key password'
    )

    parser.add_argument(
        '-t', '--threaded',
        action='store_true',
        help='Allow concurrent connections to each tunnel'
    )

    parser.add_argument(
        '-v', '--verbose',
        action='count',
        default=0,
        help='Increase output verbosity (default: {0})'.format(
            logging.getLevelName(DEFAULT_LOGLEVEL)
        )
    )

    parser.add_argument(
        '-V', '--version',
        action='version',
        version='%(prog)s {version}'.format(version=__version__),
        help='Show version number and quit'
    )

    parser.add_argument(
        '-x', '--proxy',
        type=_bindlist,
        dest='ssh_proxy',
        metavar='IP:PORT',
        help='IP and port of SSH proxy to destination'
    )

    parser.add_argument(
        '-c', '--config',
        type=str,
        default=SSH_CONFIG_FILE,
        dest='ssh_config_file',
        help='SSH configuration file, defaults to {0}'.format(SSH_CONFIG_FILE)
    )

    parser.add_argument(
        '-z', '--compress',
        action='store_true',
        dest='compression',
        help='Request server for compression over SSH transport'
    )

    parser.add_argument(
        '-n', '--noagent',
        action='store_false',
        dest='allow_agent',
        help='Disable looking for keys from an SSH agent'
    )

    parser.add_argument(
        '-d', '--host_pkey_directories',
        nargs='*',
        dest='host_pkey_directories',
        metavar='FOLDER',
        help='List of directories where SSH pkeys (in the format `id_*`) '
             'may be found'
    )
    return vars(parser.parse_args(args))
692076
def parse_args(args=None):
    """"""
    parser = argparse.ArgumentParser()

    parser.add_argument(
        '-w', '--window',
        default="pyqt5",
        choices=find_window_classes(),
        help='Name for the window type to use',
    )
    parser.add_argument(
        '-fs', '--fullscreen',
        action="store_true",
        help='Open the window in fullscreen mode',
    )
    parser.add_argument(
        '-vs', '--vsync',
        type=str2bool,
        default="1",
        help="Enable or disable vsync",
    )
    parser.add_argument(
        '-s', '--samples',
        type=int,
        default=4,
        help="Specify the desired number of samples to use for multisampling",
    )
    parser.add_argument(
        '-c', '--cursor',
        type=str2bool,
        default="true",
        help="Enable or disable displaying the mouse cursor",
    )

    return parser.parse_args(args or sys.argv[1:])
794078
def get_cmdline_varargs(argv=None):
    
    if argv is None:
        argv = sys.argv
    scriptname = argv[0]
    if scriptname == '':
        # python invoked by iteself
        pos_start = 0
        pos_end = 0
    else:
        pos_start = pos_end = 1
        for idx in range(pos_start, len(argv)):
            if argv[idx].startswith('-'):
                pos_end = idx
                break
        else:
            pos_end = len(argv)
    cmdline_varargs = argv[pos_start:pos_end]
    return cmdline_varargs
186769
def parse_args(argv):
    
    p = argparse.ArgumentParser(
        description='pypi-download-stats - Calculate detailed download stats '
                    'and generate HTML and badges for PyPI packages - '
                    '<%s>' % PROJECT_URL,
        prog='pypi-download-stats'
    )
    p.add_argument('-V', '--version', action='version',
                   version='%(prog)s ' + VERSION)
    p.add_argument('-v', '--verbose', dest='verbose', action='count',
                   default=0,
                   help='verbose output. specify twice for debug-level output.')
    m = p.add_mutually_exclusive_group()
    m.add_argument('-Q', '--no-query', dest='query', action='store_false',
                   default=True, help='do not query; just generate output '
                                      'from cached data')
    m.add_argument('-G', '--no-generate', dest='generate', action='store_false',
                   default=True, help='do not generate output; just query '
                                      'data and cache results')
    p.add_argument('-o', '--out-dir', dest='out_dir', action='store', type=str,
                   default='./pypi-stats', help='output directory (default: '
                                                './pypi-stats')
    p.add_argument('-p', '--project-id', dest='project_id', action='store',
                   type=str, default=None,
                   help='ProjectID for your Google Cloud user, if not using '
                        'service account credentials JSON file')
    # @TODO this is tied to the DiskDataCache class
    p.add_argument('-c', '--cache-dir', dest='cache_dir', action='store',
                   type=str, default='./pypi-stats-cache',
                   help='stats cache directory (default: ./pypi-stats-cache)')
    p.add_argument('-B', '--backfill-num-days', dest='backfill_days', type=int,
                   action='store', default=7,
                   help='number of days of historical data to backfill, if '
                        'missing (defaut: 7). Note this may incur BigQuery '
                        'charges. Set to -1 to backfill all available history.')
    g = p.add_mutually_exclusive_group()
    g.add_argument('-P', '--project', dest='PROJECT', action='append', type=str,
                   help='project name to query/generate stats for (can be '
                        'specified more than once; '
                        'this will reduce query cost for multiple projects)')
    g.add_argument('-U', '--user', dest='user', action='store', type=str,
                   help='Run for all PyPI projects owned by the specified'
                        'user.')
    args = p.parse_args(argv)
    return args
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
739714
def parse_command_line(argv):
    
    import textwrap

    example = textwrap.dedent("""
    Examples:
    # Simple string substitution (-e). Will show a diff. No changes applied.
    {0} -e "re.sub('failIf', 'assertFalse', line)" *.py

    # File level modifications (-f). Overwrites the files in place (-w).
    {0} -w -f fixer:fixit *.py

    # Will change all test*.py in subdirectories of tests.
    {0} -e "re.sub('failIf', 'assertFalse', line)" -s tests test*.py
    """).format(os.path.basename(argv[0]))
    formatter_class = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(description="Python mass editor",
                                     epilog=example,
                                     formatter_class=formatter_class)
    parser.add_argument("-V", "--version", action="version",
                        version="%(prog)s {}".format(__version__))
    parser.add_argument("-w", "--write", dest="dry_run",
                        action="store_false", default=True,
                        help="modify target file(s) in place. "
                        "Shows diff otherwise.")
    parser.add_argument("-v", "--verbose", dest="verbose_count",
                        action="count", default=0,
                        help="increases log verbosity (can be specified "
                        "multiple times)")
    parser.add_argument("-e", "--expression", dest="expressions", nargs=1,
                        help="Python expressions applied to target files. "
                        "Use the line variable to reference the current line.")
    parser.add_argument("-f", "--function", dest="functions", nargs=1,
                        help="Python function to apply to target file. "
                        "Takes file content as input and yield lines. "
                        "Specify function as [module]:?<function name>.")
    parser.add_argument("-x", "--executable", dest="executables", nargs=1,
                        help="Python executable to apply to target file.")
    parser.add_argument("-s", "--start", dest="start_dirs",
                        help="Directory(ies) from which to look for targets.")
    parser.add_argument("-m", "--max-depth-level", type=int, dest="max_depth",
                        help="Maximum depth when walking subdirectories.")
    parser.add_argument("-o", "--output", metavar="FILE",
                        type=argparse.FileType("w"), default=sys.stdout,
                        help="redirect output to a file")
    parser.add_argument("-g", "--generate", metavar="FILE", type=str,
                        help="generate input file suitable for -f option")
    parser.add_argument("--encoding", dest="encoding",
                        help="Encoding of input and output files")
    parser.add_argument("--newline", dest="newline",
                        help="Newline character for output files")
    parser.add_argument("patterns", metavar="pattern",
                        nargs="*",  # argparse.REMAINDER,
                        help="shell-like file name patterns to process.")
    arguments = parser.parse_args(argv[1:])

    if not (arguments.expressions or
            arguments.functions or
            arguments.generate or
            arguments.executables):
        parser.error(
            '--expression, --function, --generate or --executable missing')

    # Sets log level to WARN going more verbose for each new -V.
    log.setLevel(max(3 - arguments.verbose_count, 0) * 10)
    return arguments
102029
def run_from_argv(self, prog, subcommand, global_options, argv):
        
        self.prog_name = prog
        parser = self.create_parser(prog, subcommand)
        options, args = parser.parse_args(argv)
        self.global_options = global_options
        self.options = options
        self.args = args
        self.execute(args, options, global_options)
895984
def parse(self, argv):
        
        rv = {}
        for pattern in self.patterns:
            pattern.apply(rv, argv)
        return rv
1325741
def parse_command_line(args: List[str] = None, final: bool = True) -> List[str]:
    
    return options.parse_command_line(args, final=final)
1221945
def parse_args(args=sys.argv[1:]):
    
    parser = argparse.ArgumentParser()
    parser.add_argument('-a', '--address', help='address to listen on, default localhost',
                                default='localhost')
    parser.add_argument('-p', '--port', help='port to listen on, default 1234',
                                default=1234, type=int)
    parser.add_argument('-d', '--directory', help='directory to serve, default .',
                                default='.')
    parser.add_argument('-n', '--noindex', help='do not show directory indexes',
                                default=False, action='store_true')
    loglevel = parser.add_mutually_exclusive_group()
    loglevel.add_argument('-v', '--verbose', help='verbose logging',
                                default=False, action='store_true')
    loglevel.add_argument('-q', '--quiet', help='quiet logging',
                                default=False, action='store_true')
    return parser.parse_args(args)
1284067
def _parse_args(argv):
    
    parser = make_parser()
    args = parser.parse_args(argv)
    LOGGER.setLevel(to_log_level(args.loglevel))

    if args.inputs:
        if '-' in args.inputs:
            args.inputs = sys.stdin
    else:
        if args.list:
            _show_psrs()
        elif args.env:
            cnf = os.environ.copy()
            _output_result(cnf, args.output, args.otype or "json", None, None)
            sys.exit(0)
        else:
            parser.print_usage()
            sys.exit(1)

    if args.validate and args.schema is None:
        _exit_with_output("--validate option requires --scheme option", 1)

    return args