Runner (运行器)

支持执行子进程,使用 Foundation.Process,并异步捕获其输出。 兼容 Swift 6。

目前不支持 STDIN 流 -- 仅支持 STDOUT 和 STDERR -- 但如果我(或其他人?)遇到用例,添加起来应该很容易。

使用示例

运行并捕获标准输出 (Stdout)

let url = /* url to the executable */
let runner = Runner(for: url)

// execute with some arguments
let session = runner.run(["some", "arguments"])

// process the output asynchronously
for await l in session.stdout.lines {
  print(l)
}

在不同的工作目录中运行

// run in a different working directory
runner.cwd = /* url to the directory */
let _ = runner.run(["blah"])

转移执行

// transfer execution to the subprocess
runner.exec(url)

在路径中查找可执行文件

let runner = Runner(command: "git") /// we'll find git in $PATH if it's there
let session = runner.run("status")
print(await session.stdout.string)

运行并等待终止

let url = /* url to the executable */
let runner = Runner(for: url)

// execute with some arguments
let session = runner.run(["some", "arguments"])

// wait for termination and read state
if await session.waitUntilExit() == .succeeded {
  print("all good")
}

运行并将标准输出/标准错误 (Stdout/Stderr) 传递出去

let url = /* url to the executable */
let runner = Runner(for: url)
let session = runner.run(stdoutMode: .forward, stderrMode: .forward)
let _ = session.waitUntilExit()