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

Swift中Process执行CLI与终端执行结果不一致问题

解决Swift调用op CLI输出含ANSI转义字符的问题

这些[94m、[0m是ANSI颜色控制码——终端会解析这些代码来显示彩色文本,但直接读取进程输出时,这些原始字符会被保留,导致JSON格式失效。以下是两种解决方法:

方法一:让CLI不输出颜色(推荐)

绝大多数CLI工具都支持关闭颜色输出的参数,op CLI也不例外。只需在调用时添加--no-color参数即可:

let process = Process()
let pipe = Pipe()

process.executableURL = URL(fileURLWithPath: "/usr/local/bin/op")
// 在原有参数后追加关闭颜色的选项
process.arguments = arguments + ["--no-color"]
process.standardOutput = pipe // 一定要关联输出管道,否则无法读取内容

try process.run()
process.waitUntilExit()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)!

方法二:手动移除ANSI转义码

如果遇到不支持关闭颜色的CLI工具,可以用正则表达式过滤掉所有ANSI控制序列:

extension String {
    func stripANSI() -> String {
        // 匹配所有ANSI控制码的正则表达式
        return replacingOccurrences(of: #"\u{001B}\[[;\d]*m"#, with: "", options: .regularExpression)
    }
}

// 使用示例
let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let rawOutput = String(data: data, encoding: .utf8) {
    let cleanedOutput = rawOutput.stripANSI()
    // 现在cleanedOutput就是纯净的JSON内容
}

注意事项

  • 务必将Process的standardOutput关联到创建的Pipe,否则无法正确捕获命令输出。
  • 建议同时配置standardError管道,避免进程因错误输出缓冲区满而阻塞。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 23:40:42