macos - 在 Swift 中运行 shell 命令

标签 macos bash swift shell

我正在尝试在我的 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/

相关文章:

bash - 使用 sed/awk 插入文本中线

ios - 如何在 tableView 加载单元格上显示微调器/指示器

javascript - 将变量从 Swift 传递到 javascript 函数

swift - 如何从我的 mac 应用程序中访问终端的 $PATH 变量,它似乎使用了不同的 $PATH

java - Install4j - 关闭 MacOS X 时应用程序不会停止

cocoa - iTunes 中的音量更改通知

python - 通过 pyenv 安装的解释器不会添加到 $PATH

bash - BASH 中的 history -a 与 -w。如何替换/附加和忽略/删除重复项?

bash - 如何在远程机器上运行 SQL 查询并以 CSV 格式保存在本地

ios - UITableViewController 布局不起作用