执行 Shell 命令并获取输出。简单且健壮。
目录
将 Work 添加到 Package.swift
。
dependencies: [
.package(url: "https://github.com/flintbox/Work", from: "0.1.0")
]
Work 是 Operation 的子类,它包装了 Process 对象。
import Foundation
import Work
// Create shell commands.
let echo1 = Work(
command: "echo 1-1; sleep 1; echo 1-2; sleep 1; echo 1-3",
standardOutputHandler: { output in
print("echo1 says: \(output)")
}
)
let echo2 = Work(command: "echo 2-1; sleep 1; echo 2-2; sleep 1; echo 2-3")
// Start them synchronously.
echo1.start()
echo2.start()
// Print standard output of echo2.
print(echo2.standardOutput)
echo1 says: 1-1
echo1 says: 1-2
echo1 says: 1-3
2-1
2-2
2-3
import Foundation
import Work
// Create shell commands.
let echo1 = Work(command: "echo 1-1; sleep 1; echo 1-2; sleep 1; echo 1-3")
echo1.standardOutputHandler = { output in
print("echo1 says: \(output)")
}
echo1.completion = { result in
switch result {
case .success(_):
print("echo1 success")
case .failure(_, _):
print("echo1 failure")
}
}
let echo2 = Work(
command: "echo 2-1; sleep 1; echo 2-2; sleep 3; echo 2-3",
standardOutputHandler: { output in
print("echo2 says: \(output)")
}, completion: { result in
switch result {
case .success(_):
print("echo2 success")
case .failure(_, _):
print("echo2 failure")
}
}
)
// Start them asynchronously.
OperationQueue().addOperations([echo1, echo2], waitUntilFinished: true)
echo2 says: 2-1
echo1 says: 1-1
echo2 says: 2-2
echo1 says: 1-2
echo1 says: 1-3
echo1 success
echo2 says: 2-3
echo2 success
如果您有好的想法或建议?请不要犹豫,发起一个 pull request 或者给我发送 邮件。
希望您喜欢使用 Work 构建命令行工具!