简体   繁体   中英

How to determine if some name refers to a module without actually importing it in python?

I'm aware of two python functions that can be used to determine if some name refers to a module: pkgutil.find_loader(fullname) and pkgutil.resolve_name(name) . The first method returns a loader if the input is an importable module name. The second option returns an object whose type can be inspected to determine if it's a module. However, in both of these cases the module in question actually gets imported to python - something I do not wish to happen. Is there a way to determine if a name refers to a module (package) without actually importing it?

If a module is either a.py file, or a directory containing init .py in one of sys.path directories then below function may help:

def ismodule(fn):
    for i in sys.path:
        if os.path.isfile(os.path.join(i, fn) + '.py'): return (True, i)
        if os.path.isfile(os.path.join(i, fn, '__init__.py')): return (True,  os.path.join(i, fn))
    return (False, None)

version below covers sub-modules:

def ismodule(fn):
    fnm = fn.split('.')[0]
    for i in sys.path:
        if os.path.isfile(os.path.join(i, fnm) + '.py'): return (True, i, fnm)
        if os.path.isfile(os.path.join(i, fnm, '__init__.py')): return (True,  os.path.join(i, fnm), fnm)
    return (False, None, fnm)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM