managing-temp-scripts
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseManaging Temporary Scripts
临时脚本管理
I help you create and execute temporary scripts during workflow execution. Perfect for API integrations, data processing with specialized libraries, and creating temporary tools that execute and return results.
我可以帮助你在工作流执行过程中创建并执行临时脚本,非常适合API集成、使用专用库进行数据处理,以及创建可执行并返回结果的临时工具。
When I Activate
触发场景
I automatically activate when you:
- Need to interact with external APIs (Reddit, Twitter, GitHub, etc.)
- Want to use specific libraries not available in Claude Code
- Need to process data with custom code
- Ask "how do I call an API in a workflow?"
- Mention "temporary script", "execute code", "API client"
- Need credentials/API keys for external services
当你有以下需求时,我会自动触发:
- 需要与外部API交互(Reddit、Twitter、GitHub等)
- 想要使用Claude Code中未提供的特定库
- 需要用自定义代码处理数据
- 询问"如何在工作流中调用API?"
- 提到"临时脚本"、"执行代码"、"API客户端"
- 需要外部服务的凭证/API密钥
Key Concept
核心概念
Temporary scripts are code files that:
- Are created during workflow execution
- Execute via Bash tool
- Return results to workflow
- Are automatically cleaned up after workflow completion
Supported Languages:
- Python (with pip packages)
- Node.js/JavaScript (with npm packages)
- Shell/Bash scripts
- Ruby, Go, or any executable language
临时脚本是指以下代码文件:
- 在工作流执行期间创建
- 通过Bash工具执行
- 向工作流返回结果
- 工作流完成后自动清理
支持的语言:
- Python(支持pip包)
- Node.js/JavaScript(支持npm包)
- Shell/Bash脚本
- Ruby、Go或任何可执行语言
Quick Example
快速示例
flow
undefinedflow
undefined1. Ask for API credentials
1. 请求API凭证
AskUserQuestion:"Reddit API key needed":api_key ->
AskUserQuestion:"需要Reddit API密钥":api_key ->
2. Create Python script with embedded credentials
2. 创建包含嵌入凭证的Python脚本
general-purpose:"Create Python script: reddit_client.py with {api_key}":script_path ->
general-purpose:"创建Python脚本: reddit_client.py 并传入 {api_key}":script_path ->
3. Execute script and capture output
3. 执行脚本并捕获输出
Bash:"python3 {script_path}":reddit_data ->
Bash:"python3 {script_path}":reddit_data ->
4. Process results in workflow
4. 在工作流中处理结果
general-purpose:"Analyze {reddit_data} and create summary":analysis ->
general-purpose:"分析 {reddit_data} 并生成摘要":analysis ->
5. Cleanup happens automatically
5. 自动执行清理操作
undefinedundefinedScript Lifecycle
脚本生命周期
See script-lifecycle.md for complete details.
Overview:
1. Creation
↓
Write script to /tmp/workflow-scripts/
2. Preparation
↓
Set permissions (chmod +x)
Install dependencies if needed
3. Execution
↓
Run via Bash tool
Capture stdout/stderr
4. Data Return
↓
Parse output (JSON, CSV, text)
Pass to next workflow step
5. Cleanup
↓
Remove script files
Clean temp directories完整详情请查看script-lifecycle.md。
概述:
1. 创建
↓
将脚本写入 /tmp/workflow-scripts/
2. 准备
↓
设置权限(chmod +x)
如有需要安装依赖
3. 执行
↓
通过Bash工具运行
捕获标准输出/标准错误
4. 数据返回
↓
解析输出(JSON、CSV、文本)
传递至下一个工作流步骤
5. 清理
↓
删除脚本文件
清理临时目录Common Use Cases
常见用例
1. API Integration
1. API集成
Reddit API Client:
python
undefinedReddit API客户端:
python
undefined/tmp/workflow-scripts/reddit_client.py
/tmp/workflow-scripts/reddit_client.py
import requests
import json
import sys
api_key = sys.argv[1]
subreddit = sys.argv[2]
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get(
f'https://oauth.reddit.com/r/{subreddit}/hot.json',
headers=headers
)
print(json.dumps(response.json(), indent=2))
**In workflow:**
```flow
$script-creator:"Create reddit_client.py":script ->
Bash:"python3 {script} {api_key} programming":posts ->
general-purpose:"Parse {posts} and extract top 10 titles"import requests
import json
import sys
api_key = sys.argv[1]
subreddit = sys.argv[2]
headers = {'Authorization': f'Bearer {api_key}'}
response = requests.get(
f'https://oauth.reddit.com/r/{subreddit}/hot.json',
headers=headers
)
print(json.dumps(response.json(), indent=2))
**工作流中调用:**
```flow
$script-creator:"创建 reddit_client.py":script ->
Bash:"python3 {script} {api_key} programming":posts ->
general-purpose:"解析 {posts} 并提取前10条标题"2. Data Processing
2. 数据处理
CSV Analysis:
python
undefinedCSV分析:
python
undefined/tmp/workflow-scripts/analyze_data.py
/tmp/workflow-scripts/analyze_data.py
import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
summary = df.describe().to_json()
print(summary)
**In workflow:**
```flow
general-purpose:"Create analyze_data.py script":script ->
Bash:"pip install pandas && python3 {script} data.csv":analysis ->
general-purpose:"Interpret {analysis} and create report"import pandas as pd
import sys
df = pd.read_csv(sys.argv[1])
summary = df.describe().to_json()
print(summary)
**工作流中调用:**
```flow
general-purpose:"创建 analyze_data.py 脚本":script ->
Bash:"pip install pandas && python3 {script} data.csv":analysis ->
general-purpose:"解读 {analysis} 并生成报告"3. Web Scraping
3. 网页抓取
Article Scraper:
javascript
// /tmp/workflow-scripts/scraper.js
const axios = require('axios');
const cheerio = require('cheerio');
async function scrapeArticles(url) {
const {data} = await axios.get(url);
const $ = cheerio.load(data);
const articles = [];
$('.article').each((i, el) => {
articles.push({
title: $(el).find('.title').text(),
url: $(el).find('a').attr('href')
});
});
console.log(JSON.stringify(articles));
}
scrapeArticles(process.argv[2]);In workflow:
flow
general-purpose:"Create scraper.js":script ->
Bash:"npm install axios cheerio && node {script} https://news.site":articles ->
general-purpose:"Process {articles}"文章抓取工具:
javascript
// /tmp/workflow-scripts/scraper.js
const axios = require('axios');
const cheerio = require('cheerio');
async function scrapeArticles(url) {
const {data} = await axios.get(url);
const $ = cheerio.load(data);
const articles = [];
$('.article').each((i, el) => {
articles.push({
title: $(el).find('.title').text(),
url: $(el).find('a').attr('href')
});
});
console.log(JSON.stringify(articles));
}
scrapeArticles(process.argv[2]);工作流中调用:
flow
general-purpose:"创建 scraper.js":script ->
Bash:"npm install axios cheerio && node {script} https://news.site":articles ->
general-purpose:"处理 {articles}"Script Templates
脚本模板
See script-templates.md for complete library.
Quick templates:
- API Client (REST, GraphQL)
- Data Processing (CSV, JSON, XML)
- Web Scraping (HTML parsing)
- File Processing (PDF, images, documents)
- Database Access (PostgreSQL, MySQL, MongoDB)
- Message Queues (RabbitMQ, Kafka)
- Cloud Services (AWS S3, GCS, Azure)
完整模板库请查看script-templates.md。
快速模板:
- API客户端(REST、GraphQL)
- 数据处理(CSV、JSON、XML)
- 网页抓取(HTML解析)
- 文件处理(PDF、图片、文档)
- 数据库访问(PostgreSQL、MySQL、MongoDB)
- 消息队列(RabbitMQ、Kafka)
- 云服务(AWS S3、GCS、Azure)
Security Best Practices
安全最佳实践
See security.md for comprehensive guide.
Quick checklist:
✅ Credentials Management:
- Pass via command-line arguments (not hardcoded)
- Use environment variables for sensitive data
- Clean up after execution
✅ File Permissions:
bash
chmod 700 /tmp/workflow-scripts/script.py # Owner only✅ Output Sanitization:
- Validate script output before using
- Escape special characters
- Limit output size
✅ Dependency Management:
- Use virtual environments for Python
- Specify exact package versions
- Avoid running arbitrary code
完整指南请查看security.md。
快速检查清单:
✅ 凭证管理:
- 通过命令行参数传递(而非硬编码)
- 使用环境变量存储敏感数据
- 执行后清理凭证
✅ 文件权限:
bash
chmod 700 /tmp/workflow-scripts/script.py # 仅所有者可访问✅ 输出清理:
- 使用前验证脚本输出
- 转义特殊字符
- 限制输出大小
✅ 依赖管理:
- 为Python使用虚拟环境
- 指定精确的包版本
- 避免执行任意代码
Integration with Workflows
与工作流的集成
See integration-patterns.md for detailed patterns.
详细集成模式请查看integration-patterns.md。
Pattern 1: Simple Script Execution
模式1:简单脚本执行
flow
general-purpose:"Create script.py that fetches data":script ->
Bash:"python3 {script}":data ->
general-purpose:"Process {data}"flow
general-purpose:"创建用于获取数据的 script.py":script ->
Bash:"python3 {script}":data ->
general-purpose:"处理 {data}"Pattern 2: Script with User Input
模式2:含用户输入的脚本
flow
AskUserQuestion:"API credentials needed":creds ->
general-purpose:"Create api_client.py with {creds}":script ->
Bash:"python3 {script}":results ->
general-purpose:"Analyze {results}"flow
AskUserQuestion:"需要API凭证":creds ->
general-purpose:"创建包含 {creds} 的 api_client.py":script ->
Bash:"python3 {script}":results ->
general-purpose:"分析 {results}"Pattern 3: Parallel Script Execution
模式3:并行脚本执行
flow
general-purpose:"Create multiple API clients":scripts ->
[
Bash:"python3 {scripts.reddit}":reddit_data ||
Bash:"python3 {scripts.twitter}":twitter_data ||
Bash:"python3 {scripts.github}":github_data
] ->
general-purpose:"Merge all data sources"flow
general-purpose:"创建多个API客户端":scripts ->
[
Bash:"python3 {scripts.reddit}":reddit_data ||
Bash:"python3 {scripts.twitter}":twitter_data ||
Bash:"python3 {scripts.github}":github_data
] ->
general-purpose:"合并所有数据源"Pattern 4: Iterative Processing
模式4:迭代处理
flow
@process_batch ->
general-purpose:"Create batch_processor.py":script ->
Bash:"python3 {script} batch_{n}":results ->
(if results.has_more)~> @process_batch ~>
(if results.complete)~> general-purpose:"Finalize"flow
@process_batch ->
general-purpose:"创建 batch_processor.py":script ->
Bash:"python3 {script} batch_{n}":results ->
(if results.has_more)~> @process_batch ~>
(if results.complete)~> general-purpose:"完成处理"Script Directory Structure
脚本目录结构
/tmp/workflow-scripts/
├── {workflow-id}/ # Unique per workflow
│ ├── reddit_client.py
│ ├── data_processor.py
│ ├── requirements.txt # Python dependencies
│ ├── package.json # Node.js dependencies
│ └── .env # Environment variablesAutomatic cleanup after workflow:
bash
rm -rf /tmp/workflow-scripts/{workflow-id}/tmp/workflow-scripts/
├── {workflow-id}/ # 每个工作流唯一
│ ├── reddit_client.py
│ ├── data_processor.py
│ ├── requirements.txt # Python依赖
│ ├── package.json # Node.js依赖
│ └── .env # 环境变量工作流完成后自动清理:
bash
rm -rf /tmp/workflow-scripts/{workflow-id}Creating Scripts in Workflows
在工作流中创建脚本
Method 1: Inline Script Creation
方法1:内联创建脚本
flow
general-purpose:"Create Python script:
```python
import requests
import sys
api_key = sys.argv[1]
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': f'Bearer {api_key}'}
)
print(response.text)Save to /tmp/workflow-scripts/api_client.py":script_path ->
Bash:"python3 {script_path} {api_key}":data
undefinedflow
general-purpose:"创建Python脚本:
```python
import requests
import sys
api_key = sys.argv[1]
response = requests.get(
'https://api.example.com/data',
headers={'Authorization': f'Bearer {api_key}'}
)
print(response.text)保存至 /tmp/workflow-scripts/api_client.py":script_path ->
Bash:"python3 {script_path} {api_key}":data
undefinedMethod 2: Template-Based Creation
方法2:基于模板创建
flow
general-purpose:"Use template: api-rest-client
- Language: Python
- API: Reddit
- Auth: Bearer token
- Output: JSON
Create script in /tmp/workflow-scripts/":script ->
Bash:"python3 {script}":dataflow
general-purpose:"使用模板:api-rest-client
- 语言:Python
- API:Reddit
- 认证:Bearer令牌
- 输出:JSON
创建脚本至 /tmp/workflow-scripts/":script ->
Bash:"python3 {script}":dataMethod 3: Multi-File Scripts
方法3:多文件脚本
flow
general-purpose:"Create script package:
- main.py (entry point)
- utils.py (helper functions)
- requirements.txt (dependencies)
Save to /tmp/workflow-scripts/package/":package_path ->
Bash:"cd {package_path} && pip install -r requirements.txt && python3 main.py":dataflow
general-purpose:"创建脚本包:
- main.py(入口文件)
- utils.py(辅助函数)
- requirements.txt(依赖)
保存至 /tmp/workflow-scripts/package/":package_path ->
Bash:"cd {package_path} && pip install -r requirements.txt && python3 main.py":dataDependency Management
依赖管理
Python (pip)
Python(pip)
flow
general-purpose:"Create requirements.txt:
requests==2.31.0
pandas==2.0.0
Save to /tmp/workflow-scripts/":deps ->
general-purpose:"Create script.py":script ->
Bash:"pip install -r {deps} && python3 {script}":dataflow
general-purpose:"创建 requirements.txt:
requests==2.31.0
pandas==2.0.0
保存至 /tmp/workflow-scripts/":deps ->
general-purpose:"创建 script.py":script ->
Bash:"pip install -r {deps} && python3 {script}":dataNode.js (npm)
Node.js(npm)
flow
general-purpose:"Create package.json with dependencies":package ->
general-purpose:"Create script.js":script ->
Bash:"cd /tmp/workflow-scripts && npm install && node {script}":dataflow
general-purpose:"创建包含依赖的 package.json":package ->
general-purpose:"创建 script.js":script ->
Bash:"cd /tmp/workflow-scripts && npm install && node {script}":dataVirtual Environments
虚拟环境
flow
Bash:"python3 -m venv /tmp/workflow-scripts/venv":venv ->
general-purpose:"Create script in venv":script ->
Bash:"source /tmp/workflow-scripts/venv/bin/activate && python3 {script}":dataflow
Bash:"python3 -m venv /tmp/workflow-scripts/venv":venv ->
general-purpose:"在虚拟环境中创建脚本":script ->
Bash:"source /tmp/workflow-scripts/venv/bin/activate && python3 {script}":dataError Handling
错误处理
Capturing Errors
捕获错误
flow
Bash:"python3 {script} 2>&1":output ->
(if output.contains('Error'))~>
general-purpose:"Parse error: {output}":error ->
@review-error:"Script failed: {error}" ~>
(if output.success)~>
general-purpose:"Process {output}"flow
Bash:"python3 {script} 2>&1":output ->
(if output.contains('Error'))~>
general-purpose:"解析错误:{output}":error ->
@review-error:"脚本执行失败:{error}" ~>
(if output.success)~>
general-purpose:"处理 {output}"Retry Logic
重试逻辑
flow
@retry ->
Bash:"python3 {script}":result ->
(if result.failed)~>
general-purpose:"Wait 5 seconds" ->
@retry ~>
(if result.success)~>
general-purpose:"Process {result}"flow
@retry ->
Bash:"python3 {script}":result ->
(if result.failed)~>
general-purpose:"等待5秒" ->
@retry ~>
(if result.success)~>
general-purpose:"处理 {result}"Output Formats
输出格式
Scripts can return data in various formats:
脚本可以以多种格式返回数据:
JSON (Recommended)
JSON(推荐)
python
import json
result = {"data": [...], "status": "success"}
print(json.dumps(result))python
import json
result = {"data": [...], "status": "success"}
print(json.dumps(result))CSV
CSV
python
import csv
import sys
writer = csv.writer(sys.stdout)
writer.writerows(data)python
import csv
import sys
writer = csv.writer(sys.stdout)
writer.writerows(data)Plain Text
纯文本
python
for item in results:
print(f"{item['title']}: {item['url']}")python
for item in results:
print(f"{item['title']}: {item['url']}")Cleanup
清理操作
Automatic Cleanup
自动清理
Cleanup happens automatically after workflow completion:
flow
undefined工作流完成后会自动执行清理:
flow
undefinedAt end of workflow execution:
工作流执行结束时:
general-purpose:"Remove all scripts in /tmp/workflow-scripts/{workflow-id}"
undefinedgeneral-purpose:"删除 /tmp/workflow-scripts/{workflow-id} 下的所有脚本"
undefinedManual Cleanup
手动清理
For long-running workflows:
flow
general-purpose:"Create and execute script":result ->
general-purpose:"Process {result}":output ->
Bash:"rm -rf /tmp/workflow-scripts/{script-dir}":cleanup对于长时间运行的工作流:
flow
general-purpose:"创建并执行脚本":result ->
general-purpose:"处理 {result}":output ->
Bash:"rm -rf /tmp/workflow-scripts/{script-dir}":cleanupBest Practices
最佳实践
DO:
建议:
✅ Use unique workflow IDs for script directories
✅ Pass credentials as arguments, not hardcoded
✅ Validate and sanitize script output
✅ Use virtual environments for Python
✅ Specify exact dependency versions
✅ Return structured data (JSON preferred)
✅ Clean up after workflow completion
✅ Set restrictive file permissions
✅ Use timeouts for script execution
✅ Log script output for debugging
✅ 使用唯一的工作流ID作为脚本目录名称
✅ 通过参数传递凭证,而非硬编码
✅ 验证并清理脚本输出
✅ 为Python使用虚拟环境
✅ 指定精确的依赖版本
✅ 返回结构化数据(推荐JSON)
✅ 工作流完成后清理脚本
✅ 设置严格的文件权限
✅ 为脚本执行设置超时时间
✅ 记录脚本输出用于调试
DON'T:
禁止:
❌ Hardcode API keys in scripts
❌ Execute untrusted code
❌ Store sensitive data in script files
❌ Leave scripts after workflow
❌ Use global Python/Node packages
❌ Ignore script errors
❌ Return massive outputs (>1MB)
❌ Use system-wide directories
❌ 在脚本中硬编码API密钥
❌ 执行不可信代码
❌ 在脚本文件中存储敏感数据
❌ 工作流结束后保留脚本
❌ 使用全局Python/Node包
❌ 忽略脚本错误
❌ 返回超大输出(>1MB)
❌ 使用系统级目录
Tips for Effective Script Management
高效脚本管理技巧
-
Use Descriptive Names:not
reddit_api_client.pyscript.py -
Return Structured Data: Always use JSON when possible
-
Error Messages: Include detailed error messages in output
-
Logging: Add logging for debugging:
python
import logging
logging.basicConfig(level=logging.INFO)
logging.info(f"Fetching data from {url}")-
Validation: Validate inputs before execution
-
Timeouts: Set execution timeouts:
flow
Bash:"timeout 30 python3 {script}":data-
使用描述性名称:使用而非
reddit_api_client.pyscript.py -
返回结构化数据:尽可能使用JSON格式
-
错误信息:在输出中包含详细的错误信息
-
日志记录:添加日志用于调试:
python
import logging
logging.basicConfig(level=logging.INFO)
logging.info(f"从 {url} 获取数据")-
输入验证:执行前验证输入
-
超时设置:设置执行超时:
flow
Bash:"timeout 30 python3 {script}":dataRelated Skills
相关技能
- creating-workflows: Create workflows that use temp scripts
- executing-workflows: Execute workflows with script steps
- managing-agents: Temp agents vs temp scripts
- debugging-workflows: Debug script execution issues
- creating-workflows:创建使用临时脚本的工作流
- executing-workflows:执行包含脚本步骤的工作流
- managing-agents:临时Agent vs 临时脚本
- debugging-workflows:调试脚本执行问题
Advanced Topics
进阶主题
See detail files for:
- script-lifecycle.md - Complete lifecycle management
- script-templates.md - 20+ ready-to-use templates
- security.md - Security best practices
- integration-patterns.md - Workflow integration patterns
Ready to use temporary scripts? Just describe what API or processing you need!
详细内容请查看以下文件:
- script-lifecycle.md - 完整生命周期管理
- script-templates.md - 20+ 即用型模板
- security.md - 安全最佳实践
- integration-patterns.md - 工作流集成模式
准备好使用临时脚本了吗?只需描述你需要的API或处理需求即可!