在Swift中运行shell命令

Ada*_*hti 6 macos bash shell swift

我正在尝试在我的OSX应用程序中使用Swift运行shell命令.

运行echo之类的基本命令可以正常运行,但是后续抛出

"env:node:没有这样的文件或目录"

@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
}
Run Code Online (Sandbox Code Playgroud)

运行系统命令时,我也会收到"sh:node:command not found".

system("node -v")
Run Code Online (Sandbox Code Playgroud)

更新:

不像下面的一些建议那么好,但我设法将命令回显到一个文件中并在终端中打开并执行:

system("echo node -v > ~/installation.command; chmod +x ~/installation.command; open ~/installation.command")
Run Code Online (Sandbox Code Playgroud)

ReD*_*ion 5

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
}
Run Code Online (Sandbox Code Playgroud)

所以你可以做shell("node -v")我觉得更方便的事情:


小智 3

对此进行了更多研究。

\n\n

安装nodejs程序使用/usr/local/bin,它不包含在PATH从 Finder 启动的应用程序中:

\n\n
/usr/bin:/bin:/usr/sbin:/sbin\n
Run Code Online (Sandbox Code Playgroud)\n\n

该目录包含在via & path_helperPATH的集合中:bash/etc/profile

\n\n
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\n
Run Code Online (Sandbox Code Playgroud)\n\n

选项:

\n\n
    \n
  • 只需写/usr/local/bin/node而不是node.

  • \n
  • 通过属性调整PATH使用的。NSTaskenvironment

  • \n
  • 使用setenv更改PATHfor system\xe2\x80\x94 也会影响NSTask.

  • \n
  • bash作为登录 shell执行。有关详细信息,请参阅 手册页
  • \n
\n