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