作者:街对面的怪蜀黍 | 来源:互联网 | 2023-09-17 12:24
使用快捷指令执行Swift代码实现pod的指令-温馨提示最新的macOSMontereyBeta才支持快捷指令1、Process是一个可以执行终端命令的类,实现执行终端命令函数
温馨提示最新的macOS Monterey Beta才支持快捷指令
1、Process是一个可以执行终端命令的类,实现执行终端命令函数
extension Process {
struct Output {
var pipe:Pipe
var readData:String
init(pipe:Pipe) {
self.pipe = pipe
self.readData = String(data: pipe.fileHandleForReading.readDataToEndOfFile(), encoding: String.Encoding.utf8) ?? ""
}
}
/// 执行命令
/// - Parameters:
/// - launchPath: 命令路径
/// - arguments: 命令参数
/// - currentDirectoryPath: 命令执行目录
/// - environment: 环境变量
/// - Returns: 返回执行结果
static func executable(launchPath:String,
arguments:[String],
currentDirectoryPath:String? = nil,
environment:[String:String]? = nil)->Output{
let process = Process()
process.launchPath = launchPath
process.arguments = arguments
if let envirOnment= environment {
process.envirOnment= environment
}
if let currentDirectoryPath = currentDirectoryPath {
process.currentDirectoryPath = currentDirectoryPath
}
let pipe = Pipe()
process.standardOutput = pipe
process.launch()
return Output(pipe: pipe)
}
}
2、在编写一段执行pod的命令的代码
var envirOnment= [String:String]()
environment["PATH"] = "/opt/MonkeyDev/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Library/Apple/usr/bin:/Library/Frameworks/Mono.framework/Versions/Current/Commands"
environment["LANG"] = "en_US.UTF-8"
environment["CP_HOME_DIR"] = NSHomeDirectory().appending("/.cocoapods")
let output = Process.executable(launchPath: "/usr/local/bin/pod",
arguments: [""],
currentDirectoryPath: "",
environment: environment)
print(output.readData)
3、正式开始编写快捷指令了
重点说明一下在文本编辑状态下点击鼠标右键就可以选择插入的变量
4、运行结果如下