Running Shell Commands in Swift

I am trying to run shell commands using Swift in my OSX application.

The execution of basic commands, such as echo-work, stops, but the following throws

"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
}

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

system("node -v")

Update:

Not as good as some of the suggestions below, but I managed to execute the echo command in the file and open it and execute in the terminal:

system("echo node -v > ~/installation.command; chmod +x ~/installation.command; open ~/installation.command")
+4
source share
3 answers

Looked at it a little more.

nodejs /usr/local/bin, PATH , Finder:

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

PATH bash /etc/profile path_helper:

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

:

  • /usr/local/bin/node node.

  • PATH, NSTask environment.

  • setenv PATH system - NSTask.

  • bash . . .
+2

"sh: node:

, node .

, ~/.bash_profile , node PATH .

system bash sh -c.

, , bash . , PATH .

"env: node: "

, node . NSTask , . PATH.

NSTask, environment NSProcessInfo, NSTask environment.

+1
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
}

So, you can do shell("node -v")which is more convenient for me:

+1
source

All Articles