我正在尝试在我的 OSX 应用程序中使用 Swift 运行 shell 命令。
运行诸如 echo 之类的基本命令工作正常但以下抛出
“环境:节点:没有那个文件或目录”
@IBAction func streamTorrent(sender: AnyObject) {
shell("node", "-v")
}
func shell(args: String...) -> Int32 {
let task = NSTask()
task.launchPath = "/usr/bin/env"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
运行系统命令时,我也得到“sh: node: command not found”。
system("node -v")
更新:
不如下面的一些建议好,但我设法将命令回显到一个文件中,并在终端中打开并执行它:
system("echo node -v > ~/installation.command; chmod +x ~/installation.command; open ~/installation.command")
最佳答案
func shell(command: String) -> Int32 {
let task = NSTask()
task.launchPath = "/usr/bin/env"
task.arguments = ["bash", "-c", command]
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
所以你可以做 shell("node -v")
我觉得更方便:
关于macos - 在 Swift 中运行 shell 命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32238366/