Azure Functions导入python-tabular报错:找不到libmono
Azure Functions部署python-tabular脚本报错:RuntimeError: Could not find libmono
我有一个用于连接SSAS模型,执行分区创建、删除及刷新操作的脚本:分区操作使用pyadomd库,刷新操作使用python-tabular库(版本0.1.7)。将代码部署到Azure Functions后,触发函数时在import pytabular语句处报错,完整异常信息显示RuntimeError: Could not find libmono。请求协助解决该问题。
依赖清单(requirements.txt)
azure-functions python-tabular pyadomd msal numpy pandas pymsteams azure-storage-blob
核心代码片段
test_run.py
import pytabular from pyadomd import Pyadomd # 其他导入语句略 def func_1(): '''rest of the code here''' return df def func_2(df1): '''rest of the code here''' def main_func(): try: df1 = func_1() func_2(df1) except Exception as e: '''some code logic to retry'''
init.py
import azure.functions as func import logging import sys import os from .test_run import main_func current_dir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(current_dir)) def main(req: func.HttpRequest) -> func.HttpResponse: logging.info('Python HTTP trigger function processed a request.') try: main_func() # 请求处理逻辑略 except Exception as e: return func.HttpResponse(f"An error occurred: {str(e)}", status_code=500)
完整异常栈
Full Exception : Exception while executing function /Functions.httpTrigger ---> Microsoft.Azure.WebJobs.Script.Workers.Rpc.RpcException /Result /Failure Exception /RuntimeError /Could not find libmono / '/azure-functions-host/workers/python/3.10/LINUX/X64/azure_functions_worker/dispatcher.py', line 380, in _handle__function_load_request func = loader.load_function( '/azure-functions-host/workers/python/3.10/LINUX/X64/azure_functions_worker/utils/wrappers.py', line 44, in call return func(*args, **kwargs) '/azure-functions-host/workers/python/3.10/LINUX/X64/azure_functions_worker/loader.py', line 132, in load_function mod = importlib.import_module(fullmodname) '/usr/local/lib/python3.10/importlib/__init__.py', line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) '<frozen importlib._bootstrap>', line 1050, in _gcd_import '<frozen importlib._bootstrap>', line 1027, in _find_and_load '<frozen importlib._bootstrap>', line 1006, in _find_and_load_unlocked '<frozen importlib._bootstrap>', line 688, in _load_unlocked '<frozen importlib._bootstrap_external>', line 883, in exec_module '<frozen importlib._bootstrap>', line 241, in _call_with_frames_removed '/home/site/wwwroot/httpTrigger/__init__.py', line 9, in <module> from .refresh_automation import main_func '/home/site/wwwroot/httpTrigger/refresh_automation.py', line 6, in <module> import pytabular '/home/site/wwwroot/.python_packages/lib/site-packages/pytabular/__init__.py', line 45, in <module> import clr '/home/site/wwwroot/.python_packages/lib/site-packages/clr.py', line 6, in <module> load() '/home/site/wwwroot/.python_packages/lib/site-packages/pythonnet/__init__.py', line 36, in load set_default_runtime() '/home/site/wwwroot/.python_packages/lib/site-packages/pythonnet/__init__.py', line 22, in set_default_runtime set_runtime(clr_loader.get_mono()) '/home/site/wwwroot/.python_packages/lib/site-packages/clr_loader/__init__.py', line 21, in get_mono libmono = find_libmono(sgen) '/home/site/wwwroot/.python_packages/lib/site-packages/clr_loader/util/find.py', line 67, in find_libmono raise RuntimeError('Could not find libmono') System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Script.Description.WorkerFunctionInvoker.InvokeCore(Object[] parameters,FunctionInvocationContext context) /src/azure-functions-host/src/WebJobs.Script/Description/Workers/WorkerFunctionInvoker.cs /101 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Script.Description.FunctionInvokerBase.Invoke(Object[] parameters) /src/azure-functions-host/src/WebJobs.Script/Description/FunctionInvokerBase.cs /82 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Script.Description.FunctionGenerator.Coerce[T](Task`1 src) /src/azure-functions-host/src/WebJobs.Script/Description/FunctionGenerator.cs /225 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Host.Executors.FunctionInvoker`2.InvokeAsync[TReflected,TReturnValue](Object instance,Object[] arguments) D:\a\_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionInvoker.cs /52 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.InvokeWithTimeoutAsync(IFunctionInvoker invoker,ParameterHelper parameterHelper,CancellationTokenSource timeoutTokenSource,CancellationTokenSource functionCancellationTokenSource,Boolean throwOnTimeout,TimeSpan timerInterval,IFunctionInstance instance) D:\a\_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /581 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithWatchersAsync(IFunctionInstanceEx instance,ParameterHelper parameterHelper,ILogger logger,CancellationTokenSource functionCancellationTokenSource) D:\a\_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /527 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance,FunctionStartedMessage message,FunctionInstanceLogEntry instanceLogEntry,ParameterHelper parameterHelper,ILogger logger,CancellationToken cancellationToken) D:\a\_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /306 End of inner exception System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.ExecuteWithLoggingAsync(IFunctionInstanceEx instance,FunctionStartedMessage message,FunctionInstanceLogEntry instanceLogEntry,ParameterHelper parameterHelper,ILogger logger,CancellationToken cancellationToken) D:\a\_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /352 System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() async Microsoft.Azure.WebJobs.Host.Executors.FunctionExecutor.TryExecuteAsync(IFunctionInstance functionInstance,CancellationToken cancellationToken) D:\a\_work\1\s\src\Microsoft.Azure.WebJobs.Host\Executors\FunctionExecutor.cs /108
解决方法
原因分析
python-tabular依赖pythonnet,而pythonnet在Linux环境下需要依赖Mono运行时。Azure Functions的Linux默认运行时没有预装Mono,因此会出现找不到libmono的错误。
方案1:使用自定义Docker镜像部署Azure Functions
创建Dockerfile,基于Azure Functions Python基础镜像安装Mono:
FROM mcr.microsoft.com/azure-functions/python:4-python3.10 # 安装Mono运行时 RUN apt-get update && apt-get install -y mono-complete ENV AzureWebJobsScriptRoot=/home/site/wwwroot \ AzureFunctionsJobHost__Logging__Console__IsEnabled=true COPY requirements.txt / RUN pip install -r /requirements.txt COPY . /home/site/wwwroot
构建镜像并推送到Azure Container Registry,然后配置Azure Functions使用该自定义镜像运行。
方案2:替换python-tabular为纯Python实现
python-tabular依赖.NET生态,在Linux环境部署受限。可以改用pyadomd执行XMLA脚本完成SSAS刷新操作,示例代码:
from pyadomd import Pyadomd # 替换为你的SSAS连接字符串 connection_string = "Provider=MSOLAP;Data Source=your-ssas-server;Initial Catalog=your-model;User ID=your-user;Password=your-password;" # 替换为目标分区的XMLA刷新脚本 xmla_refresh = """<Batch xmlns="http://schemas.microsoft.com/analysisservices/2003/engine"> <Parallel> <Process xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <Object> <DatabaseID>your-model</DatabaseID> <CubeID>Model</CubeID> <MeasureGroupID>your-measure-group</MeasureGroupID> <PartitionID>your-partition</PartitionID> </Object> <Type>ProcessFull</Type> <WriteBackTableCreation>UseExisting</WriteBackTableCreation> </Process> </Parallel> </Batch>""" with Pyadomd(connection_string) as conn: with conn.cursor() as cur: cur.execute(xmla_refresh)
方案3:切换Azure Functions运行时为Windows
Windows环境预装了.NET Framework,pythonnet可直接运行,不会出现libmono缺失问题。在Azure Functions配置页面,将运行时堆栈切换为Python + Windows即可。
内容的提问来源于stack exchange,提问作者Beginner
相关产品推荐
相关产品推荐

