问题
I'm trying to build a MacOS app that can run bash commands from GUI input and have fallen at the first hurdle. I've been using this question's answer as a reference but it doesn't seem to work for me. This is my code:
import Foundation
@IBAction func buttonClicked(_ sender: Any) {
shell("ls")
}
@discardableResult
func shell(_ args: String...) -> Int32 {
let task = Process()
task.launchPath = "/Users/myUser/desktop"
task.arguments = args
task.launch()
task.waitUntilExit()
return task.terminationStatus
}
I've seen others asking about this error but they are getting it for slightly different reasons meaning I can't seem to find a fix for my particular instance of the problem.
Any ideas?
EDIT - Would also be great if someone could give me a hint as to how to get the output of the ls command back into my program, to store as a string for example.
回答1:
For a simple terminal app this is what I used
func shell(_ command: String) -> String {
let task = Process()
task.launchPath = "/bin/bash"
task.arguments = ["-c", command]
let pipe = Pipe()
task.standardOutput = pipe
task.launch()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
guard let output = String(data: data, encoding: .utf8) else {
print("Failed to produce string from \(data)")
abort()
}
return output
}
来源:https://stackoverflow.com/questions/57394288/trying-to-run-simple-bash-command-in-swift-couldnt-posix-spawn-error-13