2014-09-28 32 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