【问题标题】:OS X return to Xcode swift from shellOS X 从 shell 快速返回 Xcode
【发布时间】:2014-11-23 05:14:35
【问题描述】:

我有调用 shell 的代码。 Shell 对参数进行了一些测试,如果它们通过,它就会运行。 现在,我将任何错误发布到日志文件,但想将它们返回到我的 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 中创建的日志文件的情况下获得 shell 的输出。

【问题讨论】:

    标签: xcode macos shell swift


    【解决方案1】:

    遇到了这个。希望对您有所帮助。

    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

    【讨论】:

      猜你喜欢
      • 2017-08-20
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 2021-04-30
      • 2018-10-22
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      相关资源
      最近更新 更多