如何在GitLab Pipeline的YAML中编写多行Python脚本并实现传参
GitLab CI中遍历键值对并调用外部Python脚本的解决方案
问题分析
你在VSCode中运行正常的Python脚本,直接放到GitLab CI的script多行块中执行失败,原因是CI的script块默认执行shell命令,而非Python代码。直接写Python语句会被shell当作命令解析,导致报错。
以下是几种可行的实现方案,满足你遍历键值对并调用外部myscript.py的需求:
方案1:通过Python解释器执行代码块
将Python逻辑用python -c包裹,让shell调用Python解释器执行代码,同时用subprocess调用外部脚本:
test_multiline_script_block: stage: test_1 image: python:latest script: - | python -c " import subprocess d = {'A':123, 'B':456, 'C':789, 'D':222} for key, value in d.items(): # 调用外部脚本,注意将value转为字符串 subprocess.run(['python3', 'myscript.py', key, str(value)], check=True) "
check=True会在外部脚本执行失败时终止CI任务,方便排查问题- 如果外部脚本需要接收整数类型参数,可在
myscript.py内部自行转换
方案2:用GitLab CI变量存储键值对,shell循环处理
将键值对定义为CI变量,通过shell循环拆分并调用脚本:
方式A:用空格分隔键值对
variables: # 用冒号分隔键和值,空格分隔不同键值对 KEY_VALUE_PAIRS: "A:123 B:456 C:789 D:222" test_shell_loop: stage: test_1 image: python:latest script: - | for pair in $KEY_VALUE_PAIRS; do key=$(echo "$pair" | cut -d':' -f1) value=$(echo "$pair" | cut -d':' -f2) python3 myscript.py "$key" "$value" done
方式B:用换行分隔键值对(适合含空格的场景)
variables: KEY_VALUE_PAIRS: | A:123 B:456 C:789 D:222 test_shell_loop: stage: test_1 image: python:latest script: - | # 逐行读取变量内容,跳过空行 echo "$KEY_VALUE_PAIRS" | while read -r pair; do [ -z "$pair" ] && continue key=$(echo "$pair" | cut -d':' -f1) value=$(echo "$pair" | cut -d':' -f2) python3 myscript.py "$key" "$value" done
方案3:用外部文件存储键值对
如果键值对较多,可将其存入项目内的kv_list.txt文件(每行一个键值对),再通过shell循环读取:
第一步:创建kv_list.txt文件
A:123 B:456 C:789 D:222
第二步:CI配置脚本
test_file_based_loop: stage: test_1 image: python:latest script: - | # 逐行读取文件,跳过空行 while read -r pair; do [ -z "$pair" ] && continue key=$(echo "$pair" | cut -d':' -f1) value=$(echo "$pair" | cut -d':' -f2) python3 myscript.py "$key" "$value" done < kv_list.txt
内容的提问来源于stack exchange,提问作者hitman126
相关产品推荐
相关产品推荐

