Find the disk locations of the given named modules, printing the
    discovered paths to stdout and errors discovering paths to stderr.

    Any provided keyword arguments are passed to `identify_filepath()`.
349533
def identify_modules(*args, **kwargs):
    
    if len(args) == 1:
        path_template = "%(file)s"
        error_template = "Module '%(mod)s' not found (%(error)s)"
    else:
        path_template = "%(mod)s: %(file)s"
        error_template = "%(mod)s: not found (%(error)s)"

    for modulename in args:
        try:
            filepath = identify_filepath(modulename, **kwargs)
        except ModuleNotFound:
            exc = sys.exc_info()[1]
            sys.stderr.write(error_template % {
                'mod': modulename,
                'error': str(exc),
            })
            sys.stderr.write('\n')
        else:
            print(path_template % {
                'mod': modulename,
                'file': filepath
            })
531962
def find_path(dirs, path_to_find):
    
    for dir in dirs:
        if os.path.exists(os.path.join(dir, path_to_find)):
            return dir
    return None
434398
def iter_module_paths(modules=None):
    
    modules = modules or list(sys.modules.values())
    for module in modules:
        try:
            filename = module.__file__
        except (AttributeError, ImportError):  # pragma: no cover
            continue
        if filename is not None:
            abs_filename = os.path.abspath(filename)
            if os.path.isfile(abs_filename):
                yield abs_filename
1108395
def getFilesForName(name):
    
    if not os.path.exists(name):
        # check for glob chars
        if containsAny(name, "*?[]"):
            files = glob.glob(name)
            list = []
            for file in files:
                list.extend(getFilesForName(file))
            return list

        # try to find module or package
        name = _get_modpkg_path(name)
        if not name:
            return []

    if os.path.isdir(name):
        # find all python files in directory
        list = []
        os.path.walk(name, _visit_pyfiles, list)
        return list
    elif os.path.exists(name):
        # a single file
        return [name]

    return []
716527
def _get_plugin_module_paths(self, plugin_dir):
        '''  '''
        filepaths = [
            fp for fp in glob.glob('{}/**/*.py'.format(plugin_dir), recursive=True)
            if not fp.endswith('__init__.py')
        ]
        rel_paths = [re.sub(plugin_dir.rstrip('/') + '/', '', fp) for fp in filepaths]
        module_paths = [rp.replace('/', '.').replace('.py', '') for rp in rel_paths]

        return module_paths
109709
def is_py2_stdlib_module(m):
    
    if PY3:
        return False
    if not 'stdlib_path' in is_py2_stdlib_module.__dict__:
        stdlib_files = [contextlib.__file__, os.__file__, copy.__file__]
        stdlib_paths = [os.path.split(f)[0] for f in stdlib_files]
        if not len(set(stdlib_paths)) == 1:
            # This seems to happen on travis-ci.org. Very strange. We'll try to
            # ignore it.
            flog.warn('Multiple locations found for the Python standard '
                         'library: %s' % stdlib_paths)
        # Choose the first one arbitrarily
        is_py2_stdlib_module.stdlib_path = stdlib_paths[0]

    if m.__name__ in sys.builtin_module_names:
        return True

    if hasattr(m, '__file__'):
        modpath = os.path.split(m.__file__)
        if (modpath[0].startswith(is_py2_stdlib_module.stdlib_path) and
            'site-packages' not in modpath[0]):
            return True

    return False
1196013
def CheckForUnknownFiles(self):
		""""""
		unknown_files = self.GetUnknownFiles()
		if unknown_files:
			print "The following files are not added to version control:"
			for line in unknown_files:
				print line
			prompt = "Are you sure to continue?(y/N) "
			answer = raw_input(prompt).strip()
			if answer != "y":
				ErrorExit("User aborted")
709515
def print_filename(path):
    

    if os.path.basename(path):
        return os.path.basename(path)
    return path
256334
def find_path_package_name(thepath):
    
    module_found = False
    last_module_found = None
    continue_ = True
    while continue_:
        module_found = is_path_python_module(thepath)
        next_path = path.dirname(thepath)
        if next_path == thepath:
            continue_ = False
        if module_found:
            init_names = ['__init__%s' % suffix.lower() for suffix in _py_suffixes]
            if path.basename(thepath).lower() in init_names:
                last_module_found = path.basename(path.dirname(thepath))
            else:
                last_module_found = path.basename(thepath)
        if last_module_found and not module_found:
            continue_ = False
        thepath = next_path
    return last_module_found
446870
def get_modules(root_path):
    """"""
    for dir_path, dir_names, file_names in os.walk(root_path):
        assert dir_path[:len(root_path)] == root_path
        subdir_path = dir_path[len(root_path):]
        package_parts = list(filter(lambda x: x, subdir_path.split('/')))
        for name in file_names:
            if name.endswith('.py'):
                path = os.path.join(dir_path, name)
                pkgpath = '.'.join(package_parts)
                modpath = (pkgpath if name == '__init__.py' else
                           '.'.join(package_parts + [name[:-3]]))
                try:
                    node = ast.parse(open(path).read())
                except SyntaxError:
                    print('ERROR: Invalid syntax in %s' % path, file=sys.stderr)
                else:
                    yield (pkgpath, modpath, path, node)
474166
def pathNames(self) -> [str]:
        

        return [f.pathName for f in list(self._files.values())]
388889
def lookupmodule(self, filename):
        
        if os.path.isabs(filename) and os.path.exists(filename):
            return filename
        f = os.path.join(sys.path[0], filename)
        if os.path.exists(f) and self.canonic(f) == self.mainpyfile:
            return f
        root, ext = os.path.splitext(filename)
        origFileName = filename
        if ext == '':
            filename = filename + '.py'
        if os.path.isabs(filename):
            return filename
        for dirname in sys.path:
            while os.path.islink(dirname):
                dirname = os.path.realpath(os.path.join(
                    os.path.dirname(dirname),
                    os.readlink(dirname)))
            fullname = os.path.join(dirname, filename)
            if os.path.exists(fullname):
                return fullname
        if origFileName in sys.modules:
            return sys.modules[origFileName].__file__
        return None
792343
def _find_and_load_module(self, name, path=None):
        
        bits = name.split('.')
        while len(bits) > 1:
            # Treat the first bit as a package
            packagename = bits.pop(0)
            package = self._find_and_load_module(packagename, path)
            try:
                path = package.__path__
            except AttributeError:
                # This could be e.g. moves.
                flog.debug('Package {0} has no __path__.'.format(package))
                if name in sys.modules:
                    return sys.modules[name]
                flog.debug('What to do here?')

        name = bits[0]
        module_info = imp.find_module(name, path)
        return imp.load_module(name, *module_info)
912619
def file_finder(dirname="."):
	
	import distutils.log
	dirname = dirname or '.'
	try:
		valid_mgrs = managers.RepoManager.get_valid_managers(dirname)
		valid_mgrs = managers.RepoManager.existing_only(valid_mgrs)
		for mgr in valid_mgrs:
			try:
				return mgr.find_all_files()
			except Exception:
				e = sys.exc_info()[1]
				distutils.log.warn(
					"hgtools.%s could not find files: %s",
					mgr, e)
	except Exception:
		e = sys.exc_info()[1]
		distutils.log.warn(
			"Unexpected error finding valid managers in "
			"hgtools.file_finder_plugin: %s", e)
	return []
47514
def find_modules(module_path):
    
    if module_path.is_file():
        if module_path.suffix == '.py':
            yield module_path
    elif module_path.is_dir():
        pyfiles = glob.glob('{}/**/*.py'.format(module_path), recursive=True)
        yield from (Path(pyfile) for pyfile in pyfiles)
1158252
def find_py_files(srctree, ignore=None):
        

        if not os.path.isdir(srctree):
            yield os.path.split(srctree)
        for srcpath, _, fnames in os.walk(srctree):
            # Avoid infinite recursion for silly users
            if ignore is not None and ignore in srcpath:
                continue
            for fname in (x for x in fnames if x.endswith('.py')):
                yield srcpath, fname
704784
private boolean findFiles(String[] args, String option, Set<String> suffixes,
                              Map<String,Source> found_files, Map<String, Module> found_modules,
                              Module current_module, boolean inLinksrc)
        throws ProblemException, ProblemException
    {
        // Track which source roots, source path roots and class path roots have been added.
        Set<File> roots = new HashSet<File>();
        // Track the current set of package includes,excludes as well as excluded source files,
        // to be used in the next -src/-sourcepath/-classpath
        List<String> includes = new LinkedList<String>();
        List<String> excludes = new LinkedList<String>();
        List<String> excludefiles = new LinkedList<String>();
        List<String> includefiles = new LinkedList<String>();
        // This include is used to find all modules in the source.
        List<String> moduleinfo = new LinkedList<String>();
        moduleinfo.add("module-info.java");

        for (int i = 0; i<args.length; ++i) {
            if (args[i].equals("-i")) {
                if (i+1 >= args.length) {
                    throw new ProblemException("You have to specify a package pattern following -i");
                }
                String incl = args[i+1];
                checkPattern(incl);
                includes.add(incl);
            }
            if (args[i].equals("-x")) {
                if (i+1 >= args.length) {
                    throw new ProblemException("You have to specify a package pattern following -x");
                }
                String excl = args[i+1];
                checkPattern(excl);
                excludes.add(excl);
            }
            if (args[i].equals("-xf")) {
                if (i+1 >= args.length) {
                    throw new ProblemException("You have to specify a file following -xf");
                }
                String exclf = args[i+1];
                checkFilePattern(exclf);
                exclf = Util.normalizeDriveLetter(exclf);
                excludefiles.add(fixupSeparator(exclf));
            }
            if (args[i].equals("-if")) {
                if (i+1 >= args.length) {
                    throw new ProblemException("You have to specify a file following -xf");
                }
                String inclf = args[i+1];
                checkFilePattern(inclf);
                inclf = Util.normalizeDriveLetter(inclf);
                includefiles.add(fixupSeparator(inclf));
            }
            if (args[i].equals(option)) {
                if (i+1 >= args.length) {
                    throw new ProblemException("You have to specify a directory following "+option);
                }
                String[] root_dirs = args[i+1].split(File.pathSeparator);
                for (String r : root_dirs) {
                    File root = new File(r);
                    if (!root.isDirectory()) {
                        throw new ProblemException("\""+r+"\" is not a directory.");
                    }
                    try {
                        root = root.getCanonicalFile();
                    } catch (IOException e) {
                        throw new ProblemException(""+e);
                    }
                    if (roots.contains(root)) {
                        throw new ProblemException("\""+r+"\" has already been used for "+option);
                    }
                    if (root.equals(bin_dir)) {
                        throw new ProblemException("\""+r+"\" cannot be used both for "+option+" and -d");
                    }
                    if (root.equals(gensrc_dir)) {
                        throw new ProblemException("\""+r+"\" cannot be used both for "+option+" and -s");
                    }
                    if (root.equals(header_dir)) {
                        throw new ProblemException("\""+r+"\" cannot be used both for "+option+" and -h");
                    }
                    roots.add(root);
                    Source.scanRoot(root, suffixes, excludes, includes, excludefiles, includefiles,
                                    found_files, found_modules, current_module,
                                    findBooleanOption(args, "--permit-sources-without-package"),
                                    false, inLinksrc);
                }
            }
            if (args[i].equals("-src") ||
                args[i].equals("-sourcepath") ||
                args[i].equals("-modulepath") ||
                args[i].equals("-classpath") ||
                args[i].equals("-cp"))
            {
                // Reset the includes,excludes and excludefiles after they have been used.
                includes = new LinkedList<String>();
                excludes = new LinkedList<String>();
                excludefiles = new LinkedList<String>();
                includefiles = new LinkedList<String>();
            }
        }
        return true;
    }