Azure Function App部署后遇AttributeError:os无add_dll_directory属性
问题
使用Python 3.10.9构建Azure Function App,部署后出现错误:AttributeError: module 'os' has no attribute 'add_dll_directory'。本地Visual Studio调试正常,推测是因为函数App运行在Linux系统上,而pandas依赖的numpy调用了仅Windows支持的os.add_dll_directory方法导致的。
代码
import azure.functions as func app = func.FunctionApp() @app.function_name(name="myTimer") @app.schedule(schedule="*/15 * * * *", arg_name="myTimer", run_on_startup=True, use_monitor=False) def main(myTimer: func.TimerRequest) -> None: from batch_functions import price_data_download, position_data_download, trade_history_download, risk_checks import logging price_data_download() position_data_download() risk_checks() trade_history_download() if myTimer.past_due: logging.info('The timer is past due!') logging.info('Python timer trigger function executed.')
错误栈
Result: Failure Exception: AttributeError: module 'os' has no attribute 'add_dll_directory' Stack: File "/azure-functions-host/workers/python/3.10/LINUX/X64/azure_functions_worker/dispatcher.py", line 479, in _handle__invocation_request call_result = await self._loop.run_in_executor( File "/usr/local/lib/python3.10/concurrent/futures/thread.py", line 58, in run result = self.fn(*self.args, **self.kwargs) File "/azure-functions-host/workers/python/3.10/LINUX/X64/azure_functions_worker/dispatcher.py", line 752, in _run_sync_func return ExtensionManager.get_sync_invocation_wrapper(context, File "/azure-functions-host/workers/python/3.10/LINUX/X64/azure_functions_worker/extension.py", line 215, in _raw_invocation_wrapper result = function(**args) File "/home/site/wwwroot/function_app.py", line 9, in main from batch_functions import price_data_download, position_data_download, trade_history_download, risk_checks File "/home/site/wwwroot/batch_functions.py", line 1, in <module> import pandas as pd File "/home/site/wwwroot/pandas/__init__.py", line 24, in <module> __import__(_dependency) File "/home/site/wwwroot/numpy/__init__.py", line 112, in <module> _delvewheel_patch_1_5_1() File "/home/site/wwwroot/numpy/__init__.py", line 109, in _delvewheel_patch_1_5_1 os.add_dll_directory(libs_dir)
解决建议
- 重新生成Linux兼容的依赖清单:本地Windows环境安装的numpy是适配Windows的版本(带delvewheel的DLL补丁),部署到Linux后不兼容。可以在WSL或Linux虚拟机里创建虚拟环境,执行
pip install pandas azure-functions,再用pip freeze > requirements.txt导出依赖,用这个清单重新部署。 - 锁定兼容的numpy版本:部分高版本numpy引入的delvewheel补丁仅针对Windows,选择无需该补丁的版本,比如在
requirements.txt中指定numpy<=1.23.5,重新部署安装。 - 启用Azure远程构建:部署时开启远程构建功能,让Azure在Linux环境下自动安装适配的依赖,避免本地Windows包上传导致的兼容问题。比如用Azure CLI部署时添加
--build remote参数。 - 临时修改numpy初始化代码:如果无法立即更换版本,可手动修改numpy的
__init__.py文件,在调用os.add_dll_directory前增加系统判断:
注意:该方法仅作为临时应急方案,后续更新numpy会覆盖修改,不推荐长期使用。def _delvewheel_patch_1_5_1(): import os libs_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '.libs')) if os.name == 'nt': # 仅Windows系统执行 os.add_dll_directory(libs_dir)
内容的提问来源于stack exchange,提问作者Haakon
相关产品推荐
相关产品推荐

