Osx NSTask / Process,将standardError和standardOutput结合在一个字符串中,同时将两者分开

时间:2017-01-11 20:25:12

标签: swift macos swift2 swift3

我正在尝试获取分离的standardError输出和standardOutput字符串,但我还需要完整的字符串。以下代码将解释我的案例

合并/完整字符串:

    let task = Process()
    task.launchPath = "/usr/sbin/killall"
    task.arguments = ["Dock"]
    let pipe = Pipe()
    task.standardOutput = pipe
    task.standardError = pipe
    task.launch()
    task.waitUntilExit()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let fulloutput: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

    print(fulloutput)

分隔字符串:

    let task = Process()
    task.launchPath = "/usr/sbin/killall"
    task.arguments = ["Dock"]
    let pipe = Pipe()
    let errorpipe = Pipe()
    task.standardOutput = pipe
    task.standardError = errorpipe
    task.launch()
    task.waitUntilExit()
    let data = pipe.fileHandleForReading.readDataToEndOfFile()
    let errordata = pipe.fileHandleForReading.readDataToEndOfFile()
    let output: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String
    let erroroutput: String = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as! String

    print(output)
    print(erroroutput)

我如何组合这两个所以我得到这样的输出而不运行两次命令?:

    print(output)
    print(erroroutput)
    print(fulloutput)

谢谢!

0 个答案:

没有答案