如何将Python脚本生成的路径引用至YAML文件(Azure Pipeline场景)
自动将Data文件夹路径写入YAML的实用方案
方案1:用Python脚本直接生成目标YAML
既然你已经用Python创建了Data文件夹,直接在同一个脚本里生成数据资产的YAML配置,自动填充路径:
import shutil import os import yaml # 原有的创建文件夹代码 folderName = "../Data" current_directory = os.getcwd() final_directory = os.path.join(current_directory, folderName) if os.path.exists(final_directory): shutil.rmtree(final_directory) if not os.path.exists(final_directory): os.makedirs(final_directory) # 构建数据资产配置 data_asset_config = { "$schema": "https://azuremlschemas.azureedge.net/latest/data.schema.json", "name": "your-data-asset-name", "description": "URI folder type data asset", "type": "uri_folder", "path": final_directory } # 写入YAML文件 with open("data-asset-config.yaml", "w") as f: yaml.dump(data_asset_config, f)
生成的YAML里path会自动填充Data文件夹的绝对路径,直接在Azure Pipeline里用这个文件执行az ml data create命令即可。
方案2:通过Azure Pipeline变量传递路径
先在Pipeline里动态获取路径,再注入到YAML模板中:
- 准备一个YAML模板(比如
data-asset-template.yaml),用占位符标记路径位置:
$schema: https://azuremlschemas.azureedge.net/latest/data.schema.json name: your-data-asset-name description: URI folder type data asset type: uri_folder path: $(DATA_FOLDER_PATH)
- 在Azure Pipeline的配置文件中添加步骤,获取路径并注册数据资产:
steps: - script: | python -c "import os; print('##vso[task.setvariable variable=DATA_FOLDER_PATH]' + os.path.abspath('../Data'))" displayName: 获取Data文件夹绝对路径 - script: | az ml data create --file data-asset-template.yaml displayName: 注册URI文件夹数据资产
这里用Azure Pipeline的任务变量机制,自动把路径传递给模板,完全不需要手动指定。
方案3:用Shell脚本替换YAML占位符
如果偏好Shell脚本,可通过以下方式自动替换路径:
- 同样准备带占位符的YAML模板,比如把
path设为{{DATA_PATH}} - 在Pipeline的Shell步骤中执行:
# 获取Data文件夹的绝对路径 DATA_PATH=$(realpath ../Data) # 替换YAML中的占位符 sed -i "s|{{DATA_PATH}}|$DATA_PATH|g" data-asset-template.yaml # 注册数据资产 az ml data create --file data-asset-template.yaml
Windows环境可改用PowerShell命令实现类似逻辑:
$DATA_PATH = (Resolve-Path ../Data).Path (Get-Content data-asset-template.yaml) -replace '{{DATA_PATH}}', $DATA_PATH | Set-Content data-asset-template.yaml az ml data create --file data-asset-template.yaml
内容的提问来源于stack exchange,提问作者user14736700
相关产品推荐
相关产品推荐

