第22篇-Skill与脚本集成-在技能中调用Python-Bash脚本 📅 发布时间:2026/9/4 8:17:50 👁 浏览次数: 【Skills 系统从入门到精通】第 22 篇Skill 与脚本集成——在技能中调用 Python/Bash 脚本本篇你将学到scripts/ 目录在技能中的定位和使用方法技能正文中引用脚本的正确方式execute_code vs terminal 的选择策略环境变量透传给脚本的机制完整实战编写一个带 Python 分析脚本的技能读完本篇你将能够让技能拥有更强的数据处理能力超越简单的 shell 命令组合。一、scripts 目录的定位1.1 什么时候需要脚本大部分技能只需要 Shell 命令组合就能完成任务。但有些场景需要更复杂的逻辑场景脚本类型原因JSON 数据解析PythonShell 处理 JSON 很痛苦多行日志分析Python正则匹配上下文提取数据统计和可视化Pythonpandas matplotlib批量文件操作Python复杂的文件名和路径处理多步骤自动化Bash需要条件判断和循环1.2 scripts 目录的使用脚本放在技能的scripts/目录下~/.hermes/skills/devops/log-analysis/ ├── SKILL.md └── scripts/ ├── log_parser.py ← Python 解析脚本 └── summary.sh ← Bash 汇总脚本Procedure 步骤中引用Procedure 步骤中引用log-analysis 技能目录SKILL.md正文引用脚本scripts/log_parser.pyPython 解析脚本scripts/summary.shBash 汇总脚本二、在正文中引用脚本2.1 引用方式在 SKILL.md 的 Procedure 章节中引用脚本### Step 3: Parse complex log entries For multi-line log entries (stack traces, JSON blocks), simple grep is insufficient. Use the provided parser: bash python3 scripts/log_parser.py --input /var/log/app.log --format multilineThe parser handles:Multi-line stack tracesJSON-formatted log entriesCustom timestamp formats### 2.2 Agent 使用脚本的流程 mermaid sequenceDiagram participant A as Agent participant S as SKILL.md participant F as scripts 目录 participant T as terminal A-S: 读取正文 S--A: 发现引用 scripts/log_parser.py A-F: skill_view 获取脚本内容 F--A: 参数与用法说明 Note over A: 若正文说明已足够br/可跳过查看直接执行 A-T: 执行 python3 脚本命令 T--A: 结构化输出结果Agent 在第 3 步可能选择不加载脚本内容——如果正文的说明已经足够清楚参数和用法都写了Agent 可以直接执行。三、execute_code vs terminal3.1 两种执行方式方式工具适用场景scripts/ terminal先 skill_view 获取脚本再 terminal 执行需要复用的脚本、较长的代码execute_code直接在沙箱中执行 Python一次性代码、数据分析、快速验证3.2 选择策略用 scripts/ 的场景脚本超过 50 行会在多个步骤中被反复调用需要被其他技能或会话引用需要接受命令行参数用 execute_code 的场景内联的几行代码一次性的数据处理需要交互式探索的分析快速验证假设是否是否是否需要执行代码代码超过 50 行?scripts/ 目录terminal 执行会被反复调用?需要命令行参数或被其他技能引用?execute_code 沙箱一次性内联执行3.3 实际配合很多时候两者配合使用效果最好### Step 1: Use script for heavy parsing bash python3 scripts/log_parser.py --input app.log --output /tmp/parsed.jsonStep 2: Quick analysis with execute_codeAgent 根据 /tmp/parsed.json 的内容用 execute_code 做 ad-hoc 分析--- ## 四、实战带 Python 脚本的技能 ### 4.1 脚本编写 python # scripts/log_parser.py #!/usr/bin/env python3 Log Parser - 解析应用日志并提取结构化错误信息 Usage: python3 log_parser.py --input logfile [--format multiline|json] [--level ERROR|FATAL|WARNING] [--output outfile] import argparse import json import re import sys from collections import Counter from datetime import datetime def parse_args(): parser argparse.ArgumentParser(descriptionParse application logs) parser.add_argument(--input, requiredTrue, helpInput log file) parser.add_argument(--format, defaultstandard, choices[standard, multiline, json], helpLog format) parser.add_argument(--level, defaultERROR,FATAL, helpLog levels to extract (comma-separated)) parser.add_argument(--output, helpOutput file (default: stdout)) return parser.parse_args() def extract_errors(lines, levels, fmt): 提取错误行并处理多行栈轨迹 level_pattern |.join(levels.split(,)) pattern re.compile(rf\[.*?\]\s({level_pattern}):\s*(.)) errors [] current_error None for line in lines: match pattern.match(line) if match: if current_error: errors.append(current_error) current_error { level: match.group(1), message: match.group(2).strip(), context: [] } elif current_error and fmt multiline: # Capture continuation lines as context if not line.startswith([): current_error[context].append(line.strip()) if current_error: errors.append(current_error) return errors def summarize(errors): 生成错误统计摘要 level_counts Counter(e[level] for e in errors) message_counts Counter(e[message][:80] for e in errors) return { total_errors: len(errors), by_level: dict(level_counts), top_messages: message_counts.most_common(10) } def main(): args parse_args() with open(args.input, r, errorsreplace) as f: lines f.readlines() errors extract_errors(lines, args.level, args.format) summary summarize(errors) output json.dumps(summary, indent2, ensure_asciiFalse) if args.output: with open(args.output, w) as f: f.write(output) print(fResults written to {args.output}, filesys.stderr) else: print(output) if __name__ __main__: main()4.2 SKILL.md 中引用## Procedure ### Step 1: Extract and parse errors bash python3 scripts/log_parser.py \ --input /var/log/myapp/app.log \ --format multiline \ --level ERROR,FATAL \ --output /tmp/error_summary.jsonStep 2: Review summarycat/tmp/error_summary.json|python3-mjson.toolStep 3: Investigate top errorsBased on the top_messages in the summary, extract full context:# For each top error message, get surrounding linesgrep-B5-A10top error message/var/log/myapp/app.log### 4.3 环境变量自动透传 如果技能声明了 required_environment_variables这些变量会自动注入到脚本执行环境中 python # scripts/check_service.py import os import requests # 直接使用环境变量——不需要参数传递 api_key os.environ.get(MONITORING_API_KEY) if not api_key: print(Warning: MONITORING_API_KEY not set) sys.exit(1)Frontmatter 声明required_environment_variables.env 配置权限 600技能加载自动注入执行环境scripts/ 脚本os.environ 直接读取execute_code 沙箱本篇小结知识点核心内容scripts/ 定位存放可执行的 Python/Bash 脚本使用场景JSON 解析、多行分析、数据处理、批量操作正文引用在 Procedure 中说明脚本用途和参数execute_code vs scripts一次性用 execute_code复用脚本放 scripts/环境变量透传声明的 required_environment_variables 自动注入脚本环境脚本规范有 --help、参数校验、错误处理、结构化输出下篇预告下一篇是第五模块的避坑指南——总结技能编写中最常见的 8 大陷阱和修复方法。如果本篇内容对你有帮助欢迎点赞收藏有任何疑问欢迎在评论区交流。