如何在osx上使用swift 3获得最高输出(不是iOS)

时间:2017-02-26 08:20:38

标签: macos swift3 macos-sierra

// Playground

import Foundation

let task            = Process()
task.launchPath     = "/usr/bin/top"
task.arguments      = ["-s","2"]
let pipe            = Pipe()
task.standardOutput = pipe
task.launch()
let data            = pipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()

print(String(data: data, encoding: String.Encoding.utf8)!)

此代码使用“/ bin / ls”而不是“/ usr / bin / top”,当我把其他参数但是就像它实际上我在操场上什么都没有,它在我的xcode8项目中用“An”未被捕获的例外被提出“并且它与asm共进午餐。那么如何在变量中获得TOP输出?

1 个答案:

答案 0 :(得分:0)

实测值

// Playground

import Foundation
import PlaygroundSupport
PlaygroundPage.current.needsIndefiniteExecution = true

let task            = Process()
task.launchPath     = "/usr/bin/top"
task.arguments      = ["-s","9"]
let pipe            = Pipe()
task.standardOutput = pipe
let outHandle       = pipe.fileHandleForReading

outHandle.readabilityHandler = { pipe in
    if let line = String(data: pipe.availableData, encoding: String.Encoding.utf8) {
        // Update your view with the new text here
        print("New ouput: \(line)")
    } else {
        print("Error decoding data: \(pipe.availableData)")
    }
}

task.launch()