Skip to content
FunCoding

Search

Search docs, agents, posts, Skills and MCP servers

无头模式与输出格式

用 -p/--print 在脚本和自动化里使用 Cursor CLI:用 --force 修改文件、CURSOR_API_KEY 认证、text/json/stream-json 输出格式。

在脚本和自动化工作流里使用 Cursor CLI 做代码分析、生成和重构任务。非交互脚本用打印模式(-p、--print)。

在脚本里修改文件

把 --print 与 --force(或 --yolo)结合,在脚本里修改文件:

# 在打印模式里启用文件修改
agent -p --force "Refactor this code to use modern ES6+ syntax"

# 没有 --force 时改动只是被提议,不会被应用
agent -p "Add JSDoc comments to this file"  # 不会修改文件

# 批量处理并真正修改文件
find src/ -name "*.js" | while read file; do
  agent -p --force "Add comprehensive JSDoc comments to $file"
done

--force 标志允许智能体不经确认直接修改文件。

设置与认证

安装和认证的完整细节见安装与认证页。脚本里用 API Key:

# 为脚本设置 API Key
export CURSOR_API_KEY=your_api_key_here
agent -p "Analyze this code"

输出格式

不同脚本需要不同的输出格式,用 --output-format(只在打印模式有效,或在推断为打印模式时,如非 TTY 的 stdout 或管道 stdin):

  • text(默认):干净的、只有最终答案的回复,适合简单的代码库问题,如 agent -p "What does this codebase do?"
  • json:在运行成功完成时输出单个 JSON 对象(后跟换行);不输出增量和工具事件,文本被聚合到最终结果里。失败时进程以非零退出码退出并把错误消息写到 stderr,不会输出格式良好的 JSON 对象
  • stream-json:流式事件(配合 --stream-partial-output 可以按文本增量流式输出部分内容)

json 成功响应的结构:

{
  "type": "result",
  "subtype": "success",
  "is_error": false,
  "duration_ms": 1234,
  "duration_api_ms": 1234,
  "result": "<full assistant text>",
  "session_id": "<uuid>",
  "request_id": "<optional request id>"
}

字段:type 对终端结果总是 "result";subtype 对成功完成总是 "success";is_error 对成功响应总是 false;duration_ms 是总执行时间(毫秒);duration_api_ms 是 API 请求时间(目前等于 duration_ms);result 是完整的助手文本;session_id 是会话 UUID。需要结构化分析(如自动化代码评审)时用 --output-format json。CLI 还支持在 GitHub Actions 里运行,见官方 GitHub Actions 页。