Azure ML在线端点部署时score.py中os.makedir()触发权限错误
Azure ML在线端点创建文件夹权限错误解决方法
问题场景
实现自定义模型预测功能时,尝试在score.py的init()函数中创建本地目录,代码如下:
import os inputs_root = "inputs" outputs_root = "outputs" def init(): if not os.path.exists(inputs_root): os.mkdir(inputs_root) if not os.path.exists(outputs_root): os.mkdir(outputs_root)
部署后触发权限拒绝错误,日志信息:
2023-04-13 14:10:52,736 E [68] azmlinfsrv - Encountered Exception Traceback (most recent call last): File "/opt/miniconda/envs/amlenv/lib/python3.8/site-packages/azureml_inference_server_http/server/user_script.py", line 117, in invoke_init self._user_init() File "/var/azureml-app/avaj1870/src/score.py", line 71, in init os.mkdir(inputs_root) PermissionError: [Errno 13] Permission denied: 'inputs' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/opt/miniconda/envs/amlenv/lib/python3.8/site-packages/azureml_inference_server_http/server/aml_blueprint.py", line 111, in setup self.user_script.invoke_init() File "/opt/miniconda/envs/amlenv/lib/python3.8/site-packages/azureml_inference_server_http/server/user_script.py", line 119, in invoke_init raise UserScriptException(ex) from ex azureml_inference_server_http.server.user_script.UserScriptException: Caught an unhandled exception from the user script
问题原因
Azure ML在线端点的运行环境中,代码所在的默认工作目录没有写入权限,直接在此路径下创建文件夹会触发权限拒绝。
解决方案
使用Azure ML环境提供的可写入临时目录,这类目录由环境变量指定,修改score.py代码如下:
import os # 优先使用Azure ML提供的临时目录, fallback到系统临时目录 temp_base_dir = os.environ.get("AZUREML_TMPDIR", "/tmp") inputs_root = os.path.join(temp_base_dir, "inputs") outputs_root = os.path.join(temp_base_dir, "outputs") def init(): # 使用makedirs递归创建目录,exist_ok=True避免目录已存在时抛出异常 os.makedirs(inputs_root, exist_ok=True) os.makedirs(outputs_root, exist_ok=True)
补充说明
AZUREML_TMPDIR是Azure ML专门为推理环境分配的临时存储路径,具备完整写入权限;os.makedirs相比os.mkdir支持递归创建多级目录,结合exist_ok=True可以让代码更健壮,无需额外判断目录是否存在。
内容的提问来源于stack exchange,提问作者Batuhan Tekmen
相关产品推荐
相关产品推荐

