Return a PackageFinder respecting command-line options.

    :arg argv: Everything after the subcommand
433205
def package_finder(argv):
    
    # We instantiate an InstallCommand and then use some of its private
    # machinery--its arg parser--for our own purposes, like a virus. This
    # approach is portable across many pip versions, where more fine-grained
    # ones are not. Ignoring options that don't exist on the parser (for
    # instance, --use-wheel) gives us a straightforward method of backward
    # compatibility.
    try:
        command = InstallCommand()
    except TypeError:
        # This is likely pip 1.3.0's "__init__() takes exactly 2 arguments (1
        # given)" error. In that version, InstallCommand takes a top=level
        # parser passed in from outside.
        from pip.baseparser import create_main_parser
        command = InstallCommand(create_main_parser())
    # The downside is that it essentially ruins the InstallCommand class for
    # further use. Calling out to pip.main() within the same interpreter, for
    # example, would result in arguments parsed this time turning up there.
    # Thus, we deepcopy the arg parser so we don't trash its singletons. Of
    # course, deepcopy doesn't work on these objects, because they contain
    # uncopyable regex patterns, so we pickle and unpickle instead. Fun!
    options, _ = loads(dumps(command.parser)).parse_args(argv)

    # Carry over PackageFinder kwargs that have [about] the same names as
    # options attr names:
    possible_options = [
        'find_links',
        FORMAT_CONTROL_ARG,
        ('allow_all_prereleases', 'pre'),
        'process_dependency_links'
    ]
    kwargs = {}
    for option in possible_options:
        kw, attr = option if isinstance(option, tuple) else (option, option)
        value = getattr(options, attr, MARKER)
        if value is not MARKER:
            kwargs[kw] = value

    # Figure out index_urls:
    index_urls = [options.index_url] + options.extra_index_urls
    if options.no_index:
        index_urls = []
    index_urls += getattr(options, 'mirrors', [])

    # If pip is new enough to have a PipSession, initialize one, since
    # PackageFinder requires it:
    if hasattr(command, '_build_session'):
        kwargs['session'] = command._build_session(options)

    return PackageFinder(index_urls=index_urls, **kwargs)
1087965
def parse_args(argv=None):
    
    parent_parser = get_parent_parser()

    # Main parser
    desc = "Data Version Control"
    parser = DvcParser(
        prog="dvc",
        description=desc,
        parents=[parent_parser],
        formatter_class=argparse.RawTextHelpFormatter,
    )

    # NOTE: On some python versions action='version' prints to stderr
    # instead of stdout https://bugs.python.org/issue18920
    parser.add_argument(
        "-V",
        "--version",
        action=VersionAction,
        nargs=0,
        help="Show program's version.",
    )

    # Sub commands
    subparsers = parser.add_subparsers(
        title="Available Commands",
        metavar="COMMAND",
        dest="cmd",
        help="Use dvc COMMAND --help for command-specific help.",
    )

    fix_subparsers(subparsers)

    for cmd in COMMANDS:
        cmd.add_parser(subparsers, parent_parser)

    args = parser.parse_args(argv)

    return args
627451
def autocomplete():
    
    # Don't complete if user hasn't sourced bash_completion file.
    if 'PIP_AUTO_COMPLETE' not in os.environ:
        return
    cwords = os.environ['COMP_WORDS'].split()[1:]
    cword = int(os.environ['COMP_CWORD'])
    try:
        current = cwords[cword-1]
    except IndexError:
        current = ''
    load_all_commands()
    subcommands = [cmd for cmd, cls in command_dict.items() if not cls.hidden]
    options = []
    # subcommand
    try:
        subcommand_name = [w for w in cwords if w in subcommands][0]
    except IndexError:
        subcommand_name = None
    # subcommand options
    if subcommand_name:
        # special case: 'help' subcommand has no options
        if subcommand_name == 'help':
            sys.exit(1)
        # special case: list locally installed dists for uninstall command
        if subcommand_name == 'uninstall' and not current.startswith('-'):
            installed = []
            lc = current.lower()
            for dist in get_installed_distributions(local_only=True):
                if dist.key.startswith(lc) and dist.key not in cwords[1:]:
                    installed.append(dist.key)
            # if there are no dists installed, fall back to option completion
            if installed:
                for dist in installed:
                    print(dist)
                sys.exit(1)
        subcommand = command_dict.get(subcommand_name)
        options += [(opt.get_opt_string(), opt.nargs)
                    for opt in subcommand.parser.option_list
                    if opt.help != optparse.SUPPRESS_HELP]
        # filter out previously specified options from available options
        prev_opts = [x.split('=')[0] for x in cwords[1:cword-1]]
        options = [(x, v) for (x, v) in options if x not in prev_opts]
        # filter options by current input
        options = [(k, v) for k, v in options if k.startswith(current)]
        for option in options:
            opt_label = option[0]
            # append '=' to options which require args
            if option[1]:
                opt_label += '='
            print(opt_label)
    else:
        # show options of main parser only when necessary
        if current.startswith('-') or current.startswith('--'):
            subcommands += [opt.get_opt_string()
                            for opt in parser.option_list
                            if opt.help != optparse.SUPPRESS_HELP]
        print(' '.join([x for x in subcommands if x.startswith(current)]))
    sys.exit(1)
62943
def get_pkgfile(command):
    
    try:
        command = command.strip()

        if command.startswith('sudo '):
            command = command[5:]

        command = command.split(" ")[0]

        packages = subprocess.check_output(
            ['pkgfile', '-b', '-v', command],
            universal_newlines=True, stderr=utils.DEVNULL
        ).splitlines()

        return [package.split()[0] for package in packages]
    except subprocess.CalledProcessError as err:
        if err.returncode == 1 and err.output == "":
            return []
        else:
            raise err
36213
def parse_arguments(argv):
    
    parser = argparse.ArgumentParser(description=DESCRIPTION)
    base_parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument('-V', '--version', action='version',
                        version='taxit v' + version,
                        help='Print the version number and exit')

    parser.add_argument('-v', '--verbose',
                        action='count', dest='verbosity', default=1,
                        help='Increase verbosity of screen output (eg, -v is verbose, '
                        '-vv more so)')
    parser.add_argument('-q', '--quiet',
                        action='store_const', dest='verbosity', const=0,
                        help='Suppress output')

    ##########################
    # Setup all sub-commands #
    ##########################

    subparsers = parser.add_subparsers(dest='subparser_name')

    # Begin help sub-command
    parser_help = subparsers.add_parser(
        'help', help='Detailed help for actions using `help <action>`')
    parser_help.add_argument('action', nargs=1)
    # End help sub-command

    actions = {}

    for name, mod in subcommands.itermodules(
            os.path.split(subcommands.__file__)[0]):
        # set up subcommand help text. The first line of the dosctring
        # in the module is displayed as the help text in the
        # script-level help message (`script -h`). The entire
        # docstring is displayed in the help message for the
        # individual subcommand ((`script action -h`)).
        subparser = subparsers.add_parser(
            name,
            prog='taxit {}'.format(name),
            help=mod.__doc__.lstrip().split('\n', 1)[0],
            description=mod.__doc__,
            formatter_class=RawDescriptionHelpFormatter,
            parents=[base_parser])

        mod.build_parser(subparser)
        actions[name] = mod.action

    # Determine we have called ourself (e.g. "help <action>")
    # Set arguments to display help if parameter is set
    #           *or*
    # Set arguments to perform an action with any specified options.
    arguments = parser.parse_args(argv)
    # Determine which action is in play.
    action = arguments.subparser_name

    # Support help <action> by simply having this function call itself and
    # translate the arguments into something that argparse can work with.
    if action == 'help':
        return parse_arguments([str(arguments.action[0]), '-h'])

    return actions[action], arguments
980393
def parse_command_line(self, argv=None):
        
        argv = sys.argv[1:] if argv is None else argv
        self.argv = [py3compat.cast_unicode(arg) for arg in argv]

        # Append Provider Class to the list of configurable items.
        ProviderClass = getattr(providers, self.provider_type)
        self.classes.append(ProviderClass)

        if any(x in self.argv for x in ('-h', '--help-all', '--help')):
            self.print_help('--help-all' in self.argv)
            self.exit(0)

        if '--version' in self.argv or '-V' in self.argv:
            self.print_version()
            self.exit(0)

        # Generate a configuration file if flag is given.
        if '--generate-config' in self.argv:
            conf = self.generate_config_file()
            with open(self.config_file, 'w') as f:
                f.write(conf)
            self.exit(0)

        # If not config, parse commands.
        ## Run sanity checks.
        # Check that the minimum number of arguments have been called.
        if len(self.argv) < 2:
            raise JhubctlError(
                "Not enough arguments. \n\n"
                "Expected: jhubctl <action> <resource> <name>")

        # Check action
        self.resource_action = self.argv[0]
        if self.resource_action not in self.subcommands:
            raise JhubctlError(
                f"Subcommand is not recognized; must be one of these: {self.subcommands}")

        # Check resource
        self.resource_type = self.argv[1]
        if self.resource_type not in self.resources:
            raise JhubctlError(
                f"First argument after a subcommand must one of these"
                f"resources: {self.resources}"
            )

        # Get name of resource.
        try:
            self.resource_name = self.argv[2]
        except IndexError:
            if self.resource_action != "get":
                raise JhubctlError(
                    "Not enough arguments. \n\n"
                    "Expected: jhubctl <action> <resource> <name>")
            else:
                self.resource_name = None

        # flatten flags&aliases, so cl-args get appropriate priority:
        flags, aliases = self.flatten_flags()
        loader = KVArgParseConfigLoader(argv=argv, aliases=aliases,
                                        flags=flags, log=self.log)
        config = loader.load_config()
        self.update_config(config)
        # store unparsed args in extra_args
        self.extra_args = loader.extra_args
1076860
def _build_package_finder(self, options, index_urls, session):
        
        return PackageFinder(
            find_links=options.find_links,
            index_urls=index_urls,
            allow_all_prereleases=options.pre,
            trusted_hosts=options.trusted_hosts,
            session=session,
        )
1367259
def get_pkg_config(pkg_config_args, *packages):
    
    if not isinstance(pkg_config_args, (tuple, list)):
        pkg_config_args = [pkg_config_args]
    # Maybe we have multiple pkg-config, and maybe some of them finds it.
    for pp in find_exec_in_path("pkg-config"):
        try:
            cmd = [pp] + list(pkg_config_args) + list(packages)
            #print(" ".join(cmd))
            out = check_output(cmd, stderr=open(os.devnull, "wb"))
            return out.strip().decode("utf8").split()
        except CalledProcessError:
            pass
    return None
23084
def find_packages(path: str) -> List[str]:
    
    for root, _dir, files in os.walk(path):
        if '__init__.py' in files:
            yield root.replace("/", ".")
33414
def options(argv=[]):
    
    parser = HendrixOptionParser
    parsed_args = parser.parse_args(argv)
    return vars(parsed_args[0])
555430
function getOpts (processArgv) {
  return optimist(processArgv)
    .usage(help())
    // Show version
    .boolean("version")
    .describe("version", "Show version and exit")
    // Help options (converted to help command)
    .boolean("h")
    .describe("h", "Show help")
    .alias("h", "help")
    // Update notification control
    .boolean("no-notifier")
    .describe("no-notifier", "Disable update notifier");
}
1109533
def WhereIs(self, prog, path=None, pathext=None, reject=[]):
        
        if path is None:
            try:
                path = self['ENV']['PATH']
            except KeyError:
                pass
        elif SCons.Util.is_String(path):
            path = self.subst(path)
        if pathext is None:
            try:
                pathext = self['ENV']['PATHEXT']
            except KeyError:
                pass
        elif SCons.Util.is_String(pathext):
            pathext = self.subst(pathext)
        prog = SCons.Util.CLVar(self.subst(prog)) # support "program --with-args"
        path = SCons.Util.WhereIs(prog[0], path, pathext, reject)
        if path: return path
        return None
507159
def get_command_line_arguments():
    

    parser = argparse.ArgumentParser(add_help=False)

    parser.add_argument("-h",
                        "--help",
                        action="help",
                        help="'Displays this help message and exit.'")

    parser.add_argument("-t",
                        "--title",
                        type=unicode,
                        dest="title",
                        help="'Package title.'")

    parser.add_argument("-i",
                        "--input",
                        type=unicode,
                        dest="input",
                        help="'Input file to convert.'")

    parser.add_argument("-o",
                        "--output",
                        type=unicode,
                        dest="output",
                        help="'Output file.'")

    parser.add_argument("-c",
                        "--content_directory",
                        type=unicode,
                        dest="content_directory",
                        help="'Content directory.'")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    return parser.parse_args()
1316337
def main(argv=None):
    ''' 

    '''
    from intake.cli.bootstrap import main as _main

    return _main('Intake Catalog CLI', subcommands.all, argv or sys.argv)
1079287
def find_symlinks_cmd():
	
	from optparse import OptionParser
	from textwrap import dedent
	parser = OptionParser(usage=dedent(find_symlinks_cmd.__doc__).strip())
	options, args = parser.parse_args()
	if not args:
		args = ['.']
	root = args.pop()
	if args:
		parser.error("unexpected argument(s)")
	try:
		for symlink in find_symlinks(root):
			target = readlink(symlink)
			dir = ['', 'D'][os.path.isdir(symlink)]
			msg = '{dir:2}{symlink} --> {target}'.format(**locals())
			print(msg)
	except KeyboardInterrupt:
		pass
123860
def main(argv=None):
    
    args = _cmdline(argv)
    config.load(args.config)
    results = get_package_list(args.search_term)
    results = sorted(results, key=lambda a: sort_function(a[1]), reverse=True)
    results_normalized = list()
    last_result = None
    for result in results:
        if result[0] == last_result:
            continue
        results_normalized.append(result)
        last_result = result[0]
    print('\n'.join(["%s    -     %s" % (_[0], _[1]) for _ in results_normalized]))
    return 0
98238
def main(argv: Optional[Sequence[str]] = None, *, check: bool = True, **runargs) -> Optional[CompletedProcess]:
    
    parser = ArgumentParser(description="There are a few packages providing commands. Try e.g. `pip install scanpy-scripts`!")
    parser.set_defaults(func=parser.print_help)
    
    subparsers: DelegatingSubparsersAction = parser.add_subparsers(
        action=DelegatingSubparsersAction,
        _command='scanpy',
        _runargs={**runargs, 'check': check},
    )
    
    parser_settings = subparsers.add_parser('settings')
    parser_settings.set_defaults(func=cmd_settings)
    
    args = parser.parse_args(argv)
    return args.func()