2014-09-28 35 views
0

我有調用shell的代碼。 Shell對參數進行了一些測試,如果它們通過,它就會運行。 現在,我發佈到日誌文件中的任何錯誤,但希望他們回到我的快捷程序...OS X從shell中返回到Xcode swift

let bundle = NSBundle.mainBundle() 
    let cmd = bundle.pathForResource("model", ofType: "sh") 
    let task = NSTask() 
    task.launchPath = cmd 
    task.arguments = [ "\(arg1.stringValue)", "\(arg2.stringValue)" ] 
    task.launch() 

這工作,但我如何才能讀取日誌文件中的殼短的輸出在shell中創建。

回答

3

跑進這個。希望能幫助到你。

http://practicalswift.com/2014/06/25/how-to-execute-shell-commands-from-swift/

#!/usr/bin/env xcrun swift -i 

import Foundation 

let task = NSTask() 
task.launchPath = "/bin/echo" 
task.arguments = ["first-argument", "second-argument"] 

let pipe = NSPipe() 
task.standardOutput = pipe 
task.launch() 

let data = pipe.fileHandleForReading.readDataToEndOfFile() 
let output: String = NSString(data: data, encoding: NSUTF8StringEncoding) 

print(output) 
assert(output == "first-argument second-argument\n") 

在github上發佈的內容可能也有用一個項目:

https://github.com/kareman/SwiftShell

+0

我不能投票了嗎 - 這就是答案。 Thx – 2014-09-28 20:57:14

+0

您可以通過單擊投票箭頭下面的複選標記來接受答案。 – 2014-09-28 21:01:14