我正在寻找一种简单快捷的方法来查找包的根目录以及从.py文件的路径中找到完整的模块名称。
我希望用户选择.py并导入它而不会中断。导入模块如果它是包的一部分可能会中断。因此,我想自动将包的根所在的目录附加到sys.path(如果尚未存在),然后使用其完整的模块名称导入模块。
我没有从同一目录或该脚本运行任何地方,所以我不能使用__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
答案 0 :(得分:0)
由于namespace packages,这是不可能的 - 根据以下文件结构,无法确定baz.py
的正确包是foo.bar
还是bar
:
foo/
bar/
__init__.py
baz.py