在Swift中运行Shell命令 [英] Running shell commands in Swift

查看:401
本文介绍了在Swift中运行Shell命令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to run shell commands using Swift in my OSX app.

运行基本命令(例如echo)可以正常工作,但以下情况会引发

Running basic commands such as echo work fine but the following throws

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

"env: node: No such file or directory"

@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:not found"命令.

I also get "sh: node: command not found" when running the system command.

system("node -v")

更新:

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

Not as nice as some of the suggestions below, but I managed to echo the command into a file and have it opened and executed in terminal:

system("echo node -v > ~/installation.command; chmod +x ~/installation.command; open ~/installation.command")

推荐答案

对此进行了更多研究.

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

The nodejs installer uses /usr/local/bin, which is not included in the PATH for applications launched from Finder:

/usr/bin:/bin:/usr/sbin:/sbin

通过/etc/profile/etc/profile,该目录包含在为bash设置的PATH中. path_helper :

The directory is included in the PATH set for bash via /etc/profile & path_helper:

/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin

选项:

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

通过environment属性调整NSTask使用的PATH.

使用 setenv PATH更改为system-也将影响NSTask.

Use setenv to change the PATH for system — will also affect NSTask.

这篇关于在Swift中运行Shell命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆