从 .py 文件获取包根路径和完整模块名以便导入

3 投票
1 回答
3842 浏览
提问于 2025-04-17 15:37

我在寻找一种简单又快速的方法,从一个.py文件的路径中找到包的根目录和完整的模块名称。

我希望用户能选择一个.py文件并导入它,而不会出错。如果这个模块是包的一部分,直接导入可能会出问题。因此,我想自动把包的根目录添加到系统路径中(如果还没有添加的话),然后用完整的模块名称来导入这个模块。

我并不是在同一个目录下运行这个脚本,所以不能使用__file__之类的东西。而且我还没有导入这个模块,所以我也不能检查模块对象,因为根本没有这个对象。

这是一个可用的版本,但我想找到更简单、更快的解决方案。

def splitPathFull(path):
    folders=[]
    while 1:
        path,folder=os.path.split(path)

        if folder!="":
            folders.append(folder)
        else:
            if path!="":
                folders.append(path)

            break

    folders.reverse()
    return folders

def getPackageRootAndModuleNameFromFilePath(filePath):
    """
        It recursively looks up until it finds a folder without __init__.py and uses that as the root of the package
        the root of the package.
    """
    folder = os.path.dirname(filePath)
    if not os.path.exists( folder ):
        raise RuntimeError( "Location does not exist: {0}".format(folder) )

    if not filePath.endswith(".py"):
        return None

    moduleName = os.path.splitext( os.path.basename(filePath) )[0] # filename without extension

    #
    # If there's a __init__.py in the folder:
    #   Find the root module folder by recursively going up until there's no more __init__.py
    # Else:
    #   It's a standalone module/python script.
    #
    foundScriptRoot = False
    fullModuleName = None
    rootPackagePath = None
    if not os.path.exists( os.path.join(folder, "__init__.py" ) ):
        rootPackagePath = folder
        fullModuleName = moduleName
        foundScriptRoot = True
        # It's not in a Python package but a seperate ".py" script
        # Thus append it's directory name to sys path (if not in there) and import the .py as a module
    else:
        startFolder = folder

        moduleList = []
        if moduleName != "__init__":
            moduleList.append(moduleName)

        amountUp = 0
        while os.path.exists( folder ) and foundScriptRoot == False:

            moduleList.append ( os.path.basename(folder) )
            folder = os.path.dirname(folder)
            amountUp += 1

            if not os.path.exists( os.path.join(folder, "__init__.py" ) ):
                foundScriptRoot = True
                splitPath = splitPathFull(startFolder)
                rootPackagePath = os.path.join( *splitPath[:-amountUp] )
                moduleList.reverse()
                fullModuleName = ".".join(moduleList)

    if fullModuleName == None or rootPackagePath == None or foundScriptRoot == False:
        raise RuntimeError( "Couldn't resolve python package root python path and full module name for: {0}".format(filePath) )

    return [rootPackagePath, fullModuleName]

def importModuleFromFilepath(filePath, reloadModule=True):
    """
        Imports a module by it's filePath.
        It adds the root folder to sys.path if it's not already in there.
        Then it imports the module with the full package/module name and returns the imported module as object.
    """

    rootPythonPath, fullModuleName = getPackageRootAndModuleNameFromFilePath(filePath)

    # Append rootPythonPath to sys.path if not in sys.path
    if rootPythonPath not in sys.path:
        sys.path.append(rootPythonPath)

    # Import full (module.module.package) name
    mod = __import__( fullModuleName, {}, {}, [fullModuleName] )
    if reloadModule:
        reload(mod)

    return mod

1 个回答

0

这是不可能的,因为有一种叫做命名空间包的东西——在下面这种文件结构下,我们根本无法判断baz.py应该属于哪个包,是foo.bar还是仅仅是bar

foo/
    bar/
        __init__.py
        baz.py

撰写回答