0

I'm trying to open up a Terminal with Swift and run a python script from there. I found this function to do so:

(Get terminal output after a command swift)

    func runCommand(cmd : String, args : String...) -> (output: [String], error: [String], exitCode: Int32) {

    var output : [String] = []
    var error : [String] = []

    let task = NSTask()
    task.launchPath = cmd
    task.arguments = args

    let outpipe = NSPipe()
    task.standardOutput = outpipe
    let errpipe = NSPipe()
    task.standardError = errpipe

    task.launch()

    let outdata = outpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String.fromCString(UnsafePointer(outdata.bytes)) {
        string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
        output = string.componentsSeparatedByString("\n")
    }

    let errdata = errpipe.fileHandleForReading.readDataToEndOfFile()
    if var string = String.fromCString(UnsafePointer(errdata.bytes)) {
        string = string.stringByTrimmingCharactersInSet(NSCharacterSet.newlineCharacterSet())
        error = string.componentsSeparatedByString("\n")
    }

    task.waitUntilExit()
    let status = task.terminationStatus

    return (output, error, status)
}

I'm calling the function like it is written in the question:

let output =  runCommand("/usr/bin" , args: "python " + folderPath + selecteditem)

print of args is: "python /Users/michael/Documents/Python/testestest.py"

Which is, if I paste it into a Terminal, a valid command.

But xCode tells me: Couldn't posix_spawn: error 13


What would you suggest me to do? I'm not sure if there's not a much easier way to just launch a visible console which is running the command. Another issue I'm thinking of is that it would be great to have the output in realtime in xcode (meaning to see the output while the python script is still runnning) is this even possible?

thanks

Community
  • 1
  • 1
Michael
  • 289
  • 2
  • 5
  • 14

1 Answers1

0

python /Users/michael/Documents/Python/testestest.py works in the terminal because it is entered into /bin/bash or another shell interpreter. When running shell commands using NSTask you have 2 options:

  1. Use bash just like in the terminal.

    runCommand("/bin/bash" , args: "-c", "python " + folderPath + selecteditem)

  2. Call the executable directly.

    runCommand("/usr/bin/python" , args: folderPath + selecteditem)

If you use the 2nd option you have to know exactly where the executable is, but on the plus side you can enter each argument as a separate parameter to the runCommand function and you don't have to worry about putting escaped quotes around them like you do with bash.

kareman
  • 711
  • 1
  • 6
  • 16