子进程 1.0.1

Subprocess 1.0.1

Jamf维护。



  • 作者:
  • Cyrus Ingraham

GitHub仓库

License Build CocoaPods Platform Language Carthage compatible SwiftPM compatible Documentation

Subprocess

完整文档

使用方法

Shell类

Shell类可用于同步命令执行。

命令输入

数据输入
let inputData: Data = ...
let data = try Shell(["/usr/bin/grep", "Hello"]).exec(input: .data(inputData))
文本输入
let data = try Shell(["/usr/bin/grep", "Hello"]).exec(input: .text("Hello world"))
文件URL输入
let url = URL(fileURLWithPath: "/path/to/input/file")
let data = try Shell(["/usr/bin/grep", "foo"]).exec(input: .file(url: url))
文件路径输入
let data = try Shell(["/usr/bin/grep", "foo"]).exec(input: .file(path: "/path/to/input/file"))

命令输出

作为数据输出
let data = try Shell(["/usr/bin/sw_vers"]).exec()
作为字符串输出
let text = try Shell(["/usr/bin/sw_vers"]).exec(encoding: .utf8)
以 JSON(数组或字典)格式输出
let command = ["/usr/bin/log", "show", "--style", "json", "--last", "5m"]
let logs: [[String: Any]] = try Shell(command).execJSON())
从 JSON 解析为可解码对象
struct LogMessage: Codable {
    var subsystem: String
    var category: String
    var machTimestamp: UInt64
}
let command = ["/usr/bin/log", "show", "--style", "json", "--last", "5m"]
let logs: [LogMessage] = try Shell(command).exec(decoder: JSONDecoder())
以属性列表(数组或字典)格式输出
let command = ["/bin/cat", "/System/Library/CoreServices/SystemVersion.plist"]
let dictionary: [String: Any] = try Shell(command).execPropertyList())
从属性列表解析为可解码对象
struct SystemVersion: Codable {
    enum CodingKeys: String, CodingKey {
        case version = "ProductVersion"
    }
    var version: String
}
let command = ["/bin/cat", "/System/Library/CoreServices/SystemVersion.plist"]
let result: SystemVersion = try Shell(command).exec(decoder: PropertyListDecoder())
输出映射到其他类型
let enabled = try Shell(["csrutil", "status"]).exec(encoding: .utf8) { _, txt in txt.contains("enabled") }
输出选项
let command: [String] = ...
let errorText = try Shell(command).exec(options: .stderr, encoding: .utf8)
let outputText = try Shell(command).exec(options: .stdout, encoding: .utf8)
let combinedData = try Shell(command).exec(options: .combined)

子进程类

子进程类可用于异步命令执行。

按读取方式处理输出
let command: [String] = ...
let process = Subprocess(command)

// The outputHandler and errorHandler are invoked serially
try process.launch(outputHandler: { data in
    // Handle new data read from stdout
}, errorHandler: { data in
    // Handle new data read from stderr
}, terminationHandler: { process in
    // Handle process termination, all scheduled calls to
    // the outputHandler and errorHandler are guaranteed to
    // have completed.
})
终止时处理输出
let command: [String] = ...
let process = Subprocess(command)

try process.launch { (process, outputData, errorData) in
    if process.exitCode == 0 {
        // Do something with output data
    } else {
        // Handle failure
    }
}

安装

SwiftPM

dependencies: [
	.package(url: "https://github.com/jamf/Subprocess.git", from: "1.0.0")
]

Cocoapods

pod 'Subprocess'

Carthage

github 'jamf/Subprocess'