我正在开发一个需要运行shell脚本的OS X应用程序。以下是我的Swift代码:
func runTask(arguments: [String]) {
output.string = ""
task = NSTask()
task.launchPath = "/bin/bash"
task.arguments = arguments;
errorPipe = NSPipe()
outputPipe = NSPipe()
task.standardError = errorPipe
task.standardOutput = outputPipe
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didCompleteReadingFileHandle(_:)), name: NSFileHandleReadCompletionNotification, object: task.standardOutput!.fileHandleForReading)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(didCompleteReadingFileHandle(_:)), name: NSFileHandleReadCompletionNotification, object: task.standardError!.fileHandleForReading)
errorPipe.fileHandleForReading.readInBackgroundAndNotify()
outputPipe.fileHandleForReading.readInBackgroundAndNotify()
task.launch()
}
func didCompleteReadingFileHandle(sender: NSNotification) {
let data: NSData = sender.userInfo![NSFileHandleNotificationDataItem] as! NSData;
let string = NSString(data: data, encoding: NSUTF8StringEncoding)!
// The output property is a NSTextView object
output.string?.appendContentsOf(String(string))
}
现在我尝试调用runTask
方法:
runTask(["/bin/echo", "1234"])
它显示以下错误:
/bin/echo: /bin/echo: cannot execute binary file
现在我回到终端并输入echo 1234
,它完美运行没有任何问题,那么如何让它工作呢?谢谢。