You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python文本检查程序的退出码存入变量并传入YAML?

实现步骤

1. 捕获Python脚本的退出码

在bash/zsh这类shell环境里,运行完Python脚本后,系统会自动把退出码存在内置变量$?里,直接将它赋值给自定义变量即可:

# 执行你的检查脚本
python check_test_word.py
# 将退出码存入自定义变量
EXIT_CODE=$?

2. 将变量传入YAML文件

方式一:用shell工具替换模板

先创建一个带占位符的YAML模板文件(比如template.yaml):

check_status: ${EXIT_CODE}
# 其他配置项示例
app_name: demo_service

然后用envsubst命令替换占位符,生成最终的YAML文件:

envsubst < template.yaml > final_config.yaml

方式二:Python脚本内直接生成YAML

如果不想依赖shell变量,可直接在检查脚本里完成逻辑后生成YAML:

import yaml

# 你的检查逻辑
with open("target_file.txt", "r", encoding="utf-8") as f:
    has_target_word = "test" in f.read()

exit_code = 0 if has_target_word else 1

# 生成YAML内容并写入文件
config_data = {"check_exit_code": exit_code}
with open("config.yaml", "w", encoding="utf-8") as f:
    yaml.dump(config_data, f, default_flow_style=False)

# 最后返回退出码
exit(exit_code)

方式三:自动化场景(如Ansible)

如果是用Ansible做自动化编排,可通过register捕获脚本返回码,再写入YAML:

- name: 执行检查脚本
  command: python /path/to/check_test_word.py
  register: script_result

- name: 生成配置YAML
  copy:
    content: |
      check_result: {{ script_result.rc }}
    dest: /etc/app/config.yaml

内容的提问来源于stack exchange,提问作者Zykxpython

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 09:25:34