我正在寻找一种在 Swift (macOS) 中运行终端命令的方法。我遇到了this发布,但我似乎无法获得任何解决方案。我正在尝试从我的应用程序关闭我的 mac,就像您可以从终端执行的那样(osascript -e 'tell app "loginwindow"to «event aevtrsdn»'
),但每当我这样做时,我都会得到错误:无法 posix_spawn:错误 13。
我正在使用这段代码:
func shell(launchPath: String, arguments: [String] = []) -> (String? , Int32) {
let task = Process()
task.launchPath = launchPath
task.arguments = arguments
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String(data: data, encoding: .utf8)
task.waitUntilExit()
return (output, task.terminationStatus)
}
我这样调用它:
let z = shell(launchPath: "/usr/bin/osascript", arguments: ["-e", "\'tell app \"loginwindow\" to «event aevtrsdn»\'"])
有什么帮助吗?
最佳答案
你的代码是正确的,但你不能包含第二个参数 在单引号中:
let z = shell(launchPath: "/usr/bin/osascript", arguments: ["-e", "tell app \"loginwindow\" to «event aevtrsdn»"])
只有在从 shell 执行程序时才需要这样做。
Process
将给定的参数直接传递给生成的可执行文件,
无需 shell 解释。
关于 swift +终端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42780963/